8

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] => [email protected] 
   [email] => [email protected] 
   [subject] => Magento Commerce
   [headers] => array(
            [reply_to] => [email protected]
            )
   [body] => {{template config_path="design/email/header_template"}}
              {{depend Magento Commerce}} Magento Commerce {{/depend}}
                Name:   ABC
                Email:  [email protected]
                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!!

2 Answers 2

12

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 = '[email protected]';

                $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();
9
  • 1
    thank a lot. i will try it tell you result
    – xanka
    Commented Jul 6, 2016 at 10:07
  • the mail sent empty Commented Jan 19, 2017 at 11:57
  • same issue .. its empty ... did you find any solution @MohammedGomma
    – Adnan
    Commented May 3, 2017 at 10:52
  • @FredOroskoDias did you also get the empty email
    – Adnan
    Commented May 3, 2017 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 :) Commented May 4, 2017 at 12:39
10

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' => '[email protected]'])
                ->addTo(['[email protected]', '[email protected]'])
                ->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
4
  • i am getting this error "Template file 'daily_status_template.html' is not found." Commented Apr 3, 2019 at 14:17
  • @sumeetbajaj check your etc/email_templates.xml, filename and path to it, and setTemplateIdentifier() Commented Apr 3, 2019 at 17:24
  • 1
    thanks for your reply,i solved my problem using this - magento.stackexchange.com/questions/268608/… Commented Apr 4, 2019 at 6:56
  • 1
    thanks @FredOroskoDias it will very useful and simple steps Commented Sep 2, 2021 at 11:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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