6

In magento2 send email with contact module use:

$transport = $this->_transportBuilder
                ->setTemplateIdentifier($this->scopeConfig->getValue(self::XML_PATH_EMAIL_TEMPLATE, $storeScope))
                ->setTemplateOptions(
                    [
                        'area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE,
                        'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
                    ]
                )
                ->setTemplateVars(['data' => $postObject])
                ->setFrom($this->scopeConfig->getValue(self::XML_PATH_EMAIL_SENDER, $storeScope))
                ->addTo($this->scopeConfig->getValue(self::XML_PATH_EMAIL_RECIPIENT, $storeScope))
                ->setReplyTo($post['email'])
                ->getTransport();
$transport->sendMessage();  

So i have create custom send email it not have template. but i don't know how do send email with transportBuilder is true.

this's data i want send.

$myData = Array ( 
   [to] => xxx@gmail.com 
   [email] => admin@gmail.com 
   [subject] => Magento Commerce
   [headers] => array(
            [reply_to] => admin@gmail.com
            )
   [body] => {{template config_path="design/email/header_template"}}
              {{depend Magento Commerce}} Magento Commerce {{/depend}}
                Name:   ABC
                Email:  abc@gmail.com
                Subject:    Magento Commerce
                Message:    Sample text.
            {{template config_path="design/email/footer_template"}}
 [type] => text/html
  [attachments] => 
) 

How do i can send email with $myData use transportBuilder. Many thank!!

10

You need to create etc/email_templates.xml add below code

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Email:etc/email_templates.xsd">
    <template id="myemail_email_template" label="My Label" file="myemail.html" type="text" module="Modulename_Namespace" area="frontend"/>
</config>

Now you need to add file in your module at view/frontend/email/myemail.html

<!--@subject Promopoup@-->
{{trans "My var: %myVar" myVar=$data.myvar}}

myemail.html is declared in etc/email_templates.xml

Now mail sending code as below:

                $emailTemplateVariables = array();
                $emailTempVariables['myvar'] = $myvar;

                $senderName = 'test';

                $senderEmail = 'sender@test.com';

                $postObject = new \Magento\Framework\DataObject();
                $postObject->setData($emailTempVariables);

                $sender = [
                            'name' => $senderName,
                            'email' => $senderEmail,
                            ];

                $transport = $this->_transportBuilder->setTemplateIdentifier('myemail_email_template')
                ->setTemplateOptions(['area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID])
                ->setTemplateVars(['data' => $postObject])
                ->setFrom($sender)
                ->addTo($email)
                ->setReplyTo($senderEmail)            
                ->getTransport();               
                $transport->sendMessage();
  • thank a lot. i will try it tell you result – xanka Jul 6 '16 at 10:07
  • the mail sent empty – Mohammed Gomma Jan 19 '17 at 11:57
  • same issue .. its empty ... did you find any solution @MohammedGomma – Adnan May 3 '17 at 10:52
  • @FredOroskoDias did you also get the empty email – Adnan May 3 '17 at 10:52
  • @Adnan please check my answer below. Code which I post is working. If you have troubles on your side - install MailCatcher or MailHog and look what's happen. Also try simple php script with mail() function - maybe your sendmail isn't working :) – Fred Orosko Dias May 4 '17 at 12:39
6

Original question was about not using template (as I got it) but I'm not sure. Best practice I assume is to use email template.

Here is an example of my extension which sends emails every day (cronjob isn't included)

registration.php

<?php

    \Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE,
        'ImaginationMedia_ReportSender',
        __DIR__
    );

etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="ImaginationMedia_ReportSender" setup_version="1.1.0" />
</config>

etc/email_templates.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Email:etc/email_templates.xsd">
    <template id="daily_status_template"
              label="Daily Sales by ImaginationMedia"
              file="daily_status_template.html" type="html"
              module="ImaginationMedia_ReportSender" area="frontend"/>
</config>

etc/adminhtml/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="admin">
        <route id="reportsender" frontName="reportsender">
            <module name="ImaginationMedia_ReportSender" />
        </route>
    </router>
</config>

view/frontend/email/daily_status_template.html

<!--@subject {{trans "Sales Report from Our Client"}} @-->

<h3>Report from {{var data.report_date|raw}}</h3>

<p><b>Number of orders:</b> {{var data.orders_count|raw}}</p>
<p><b>Items count:</b> {{var data.order_items_count|raw}}</p>
<p><b>Average items per order:</b> {{var data.avg_items|raw}}</p>

Model/ReportSend.php

<?php

    namespace ImaginationMedia\ReportSender\Model;

    use Magento\Framework\Mail\Template\TransportBuilder;

    class ReportSend {

        public function __construct(
            TransportBuilder $transportBuilder,
        ) {
            $this->transportBuilder = $transportBuilder;
        }

        public function execute() {
            $report = [
                'report_date' => date("j F Y", strtotime('-1 day')),
                'orders_count' => rand(1, 10),
                'order_items_count' => rand(1, 10),
                'avg_items' => rand(1, 10)
            ];

            $postObject = new \Magento\Framework\DataObject();
            $postObject->setData($report);

            $transport = $this->transportBuilder
                ->setTemplateIdentifier('daily_status_template')
                ->setTemplateOptions(['area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID])
                ->setTemplateVars(['data' => $postObject])
                ->setFrom(['name' => 'Robot','email' => 'robot@server.com'])
                ->addTo(['fred@server.com', 'otherguy@server.com'])
                ->getTransport();
            $transport->sendMessage();
        }
    }

Controller/Adminhtml/ReportSender.php

<?php

    namespace ImaginationMedia\ReportSender\Controller\Adminhtml\ReportSender;

    use Magento\Backend\App\Action\Context;
    use ImaginationMedia\ReportSender\Model\ReportSend;

    class Index extends \Magento\Backend\App\Action {

        public function __construct(
            Context $context,
            ReportSend $reportSend
        ) {
            parent::__construct($context);
            $this->reportSend = $reportSend;
        }

        public function execute() {
            $this->reportSend->execute();
            echo 'Email sent!';
        }
    }

And finally to test sending your emails use this link (your security keys should be off for this trick):

http://yourwebsite.dev/admin/reportsender/reportsender/index

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.