Magento 2用代码发送邮件

6.58K 浏览开发笔记

Magento 2用代码发送邮件

首先,在 NameSpace/ModuleName/etc/adminhtml/system.xml 文件中的section 和 group创建配置字段,如下所示:

<?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nOnamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
        <system>         
            <section id="Custom">             
                <group id="email">                 
                    <field id="email_template_field_id" translate="label comment" type="select" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1">
                        <label>Label Of Your Field</label>
                        <source_model>MagentoConfigModelConfigSourceEmailTemplate</source_model>
                         <!-- This model return all transactional email template list of magento -->
                    </field>
                </group>
            </section>
        </system>
    </config>
XML

然后在后台 MARKETING - Communications - Email Templates 里创建一个邮件模板,名字叫email_template_field_id ,在那里我们可以选择使用哪个电子邮件模板。

在模块的 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="email_template_id" label="Label Of Your Template File" file="your_email_template.html" type="html" module="NameSpace_ModuleName" area="frontend"/>
    </config>
XML

在 view/frontend/email 目录下创建电子邮件模板文件,作为email_template.xml文件中指定的名称。在这里,我们将使用 email_template.html 名称作为电子邮件模板。其中第一行的@subject后面的内容为发送邮件的标题。$myvar1,$myvar2……是向邮件模版传递的变量,通过数组的形式传递。

<@ Subject Of your email  @-->
<@ { "var this.getUrl($store, 'admin')":"Warehouse Account URL", "var customer.email":"Customer Email", "var customer.name":"Customer Name" } @-->
{{template config_path="design/email/header_template"}}  
<!-- pathe of template header-->
<!-- here $myvar1 , $myvar2, $myvar3, $myvar4, $myvar5, $myvar6 are variables in which we asssign values when we use this template for send mail-->
<!-- you can Modify content of template according to your requirement-->
<table>     
    <tr class="email-intro">         
        <td>             
            <p class="greeting">{{trans "%customer_name," customer_name=$myvar3}}</p>
            <p>{{trans "Your custom message."}} {{trans 'Your custom message <a href="%account_url">logging into your account</a>.' account_url=$this.getUrl($store,'admin',[_nosid:1]) |raw}}</p>
        </td>     
    </tr>     
    <tr class="email-summary">
        <td>             
            <h1>{{trans 'Your Order <span class="no-link">#%increment_id</span>' increment_id=$myvar1 |raw}}</h1>
            <p>{{trans 'Placed on <span class="no-link">%created_at</span>' created_at=$myvar2 |raw}}</p>
        </td>     
    </tr>     
    <tr class="email-information">
        <td>
            <table class="order-details">
            <tr>
            <td class="address-details">
               <h3>{{trans "Billing Info"}}</h3>
               <p>{{var myvar4|raw}}</p>
            </td>
            </tr>
            </table>
            <table class="email-items">
            <thead>
            <tr>
            <th class="item-info">{{trans "Item"}}</th>
            <th class="item-info">{{trans "Sku"}}</th>
            </tr>
            </thead>
            <tbody>
            {{var myvar8|raw}}
            </tbody>
            </table>
        </td>
    </tr>
    </table>
    {{template config_path="design/email/footer_template"}}  <!--footer of template-->
HTML

现在模板已经准备好了,我们在需要发送邮件的地方添加以下代码,其中$receiverInfo 和 $senderInfo 分别为收件人和发件人的地址。

   /* Here we prepare data for our email  */    
   /* Receiver Detail  */    
   $receiverInfo = [ 'name' => 'Reciver Name', 'email' => 'receiver@mallol.cn'];    
   /* Sender Detail  */    
   $senderInfo = [ 'name' => 'Sender Name','email' => 'sender@mallol.cn'];    
   /* Assign values for your template variables  */    
   $emailTemplateVariables = array();    
   $emailTempVariables['myvar1'] = $variablevalue1;    
   $emailTempVariables['myvar2'] = $variablevalue2; 
   ...
   ...
   ...
   try{        
   /* call send mail method from helper or where you define it*/         
       $this->_objectManager->get('NameSpaceModuleNmaeHelperEmail')->MailSendMethod($emailTempVariables,$senderInfo,$receiverInfo);        
   
   } catch (Exception $e) {                
       $this->_logger->error($e->getMessage());                
       return false;            
   }
PHP

我们创建一个助手函数来实现邮件发送功能。文件名 Helper/Email.php

<?php
namespace NameSpaceModuleNameHelper;  
/**  * Custom Module Email helper  */
class Email extends MagentoFrameworkAppHelperAbstractHelper{     
    const XML_PATH_EMAIL_TEMPLATE_FIELD  =&#39;section/group/your_email_template_field_id&#39;;         
    /* Here section and group refer to name of section and group where you create this field in configuration*/       
    /**      
    * @var MagentoFrameworkAppConfigScopeConfigInterface      
    */     
    protected $_scopeConfig;       
    /**      
    * Store manager      
    *      
    * @var MagentoStoreModelStoreManagerInterface      
    */     protected $_storeManager;       
    /**      
    * @var MagentoFrameworkTranslateInlineStateInterface      
    */     
    protected $inlineTranslation;       
    /**      
    * @var MagentoFrameworkMailTemplateTransportBuilder      
    */     
    protected $_transportBuilder;           
    /**      
    * @var string     
    */     
    protected $temp_id;       
    /**     
    * @param MagentoFrameworkAppHelperContext $context     
    * @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig     
    * @param MagentoStoreModelStoreManagerInterface $storeManager     
    * @param MagentoFrameworkTranslateInlineStateInterface $inlineTranslation     
    * @param MagentoFrameworkMailTemplateTransportBuilder $transportBuilder     
    */     
    public function __construct(         
         MagentoFrameworkAppHelperContext $context,        
         MagentoStoreModelStoreManagerInterface $storeManager,         
         MagentoFrameworkTranslateInlineStateInterface $inlineTranslation,         
         MagentoFrameworkMailTemplateTransportBuilder $transportBuilder     
    ) {         
        $this->_scopeConfig = $context;         
        parent::__construct($context);         
        $this->_storeManager = $storeManager;         
        $this->inlineTranslation = $inlineTranslation;         
        $this->_transportBuilder = $transportBuilder;      
    }       
    /**      
    * Return store configuration value of your template field that which id you set for template      
    *      
    * @param string $path      
    * @param int $storeId      
    * @return mixed      
    */     
    protected function getConfigValue($path, $storeId)     {         
        return $this->scopeConfig->getValue($path,MagentoStoreModelScopeInterface::SCOPE_STORE,$storeId);
    }       
    /**      
    * Return store      
    *      
    * @return Store      
    */     
    public function getStore()     {
        return $this->_storeManager->getStore();     
    }       
    /**      
    * Return template id according to store      
    *      
    * @return mixed      
    */     
    public function getTemplateId($xmlPath)     {
        return $this->getConfigValue($xmlPath, $this->getStore()->getStoreId());
    }       
    /**      
    * [generateTemplate description]  with template file and tempaltes variables values                      
    * @param  Mixed $emailTemplateVariables       
    * @param  Mixed $senderInfo                   
    * @param  Mixed $receiverInfo                 
    * @return void      
    */     
    public function generateTemplate($emailTemplateVariables,$senderInfo,$receiverInfo)     {
        $template =  $this->_transportBuilder->setTemplateIdentifier($this->temp_id)->setTemplateOptions([
        'area' => MagentoFrameworkAppArea::AREA_FRONTEND, /* here you can defile area and store of template for which you prepare it */
        'store' => $this->_storeManager->getStore()->getId(),
        ])->setTemplateVars($emailTemplateVariables)
        ->setFrom($senderInfo)
        ->addTo($receiverInfo['email'],$receiverInfo['name']); 
        return $this;             
    }       
    /**      
    * [sendInvoicedOrderEmail description]                        
    * @param  Mixed $emailTemplateVariables       
    * @param  Mixed $senderInfo                   
    * @param  Mixed $receiverInfo                 
    * @return void      
    */     
    /* your send mail method*/     
    public function MailSendMethod($emailTemplateVariables,$senderInfo,$receiverInfo)     {
        $this->temp_id = $this->getTemplateId(self::XML_PATH_EMAIL_TEMPLATE_FIELD);
        $this->inlineTranslation->suspend();
        $this->generateTemplate($emailTemplateVariables,$senderInfo,$receiverInfo);
        $transport = $this->_transportBuilder->getTransport();
        $transport->sendMessage();
        $this->inlineTranslation->resume();
    }  
}
PHP

邮件模板循环数组变量

创建 view/layout/order_items.xml 文件,

<?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nOnamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" label="Low Stock Items" design_abstraction="custom">
        <body>         
            <block class="MagentoFrameworkViewElementTemplate" name="order_items" template="NameSpace_ModuleName::order_items.phtml"/>     
        </body>
    </page>
XML

创建 view/templates/order_items.phtml 文件,

<?php 
    $items = $block->getItems() 
?> 
<table class="email-items">
    <thead>
    <tr>
    <th class="item-id">
    <?= /* @escapeNotVerified */  __('ID'); ?>
    </th>
    <th class="item-name">
    <?= /* @escapeNotVerified */  __('Name'); ?> 
    </th>
    <th class="item-sku">
    <?= /* @escapeNotVerified */  __('Sku'); ?>
    </th>
    <th class="item-qty">
    <?= /* @escapeNotVerified */  __('Quantity'); ?>         
    </th>         
    <th class="item-date">             
    <?= /* @escapeNotVerified */  __('Date'); ?>
    </th>     
    </tr>     
    </thead>     
    <tbody>     
    <?php foreach ($items as $item): ?>         
        <tr>             
        <td><?php echo $item->getData('entity_id'); ?></td>
        <td><?php echo $item->getData('name'); ?></td>
        <td><?php echo $item->getData('sku'); ?></td>
        <td><?php echo (int)$item->getData('qty'); ?></td>
        <td><?php echo $item->getData('updated_at'); ?></td>
        </tr>     
    <?php endforeach; ?>     
</tbody>
</table>

如有问题请留言,谢谢。

0