Magento 2用代码发送邮件

7.44K 浏览开发笔记

Magento 2用代码发送邮件

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


    
                 
                         
                                 
                    
                        
                        MagentoConfigModelConfigSourceEmailTemplate
                         
                    
                
            
        
    
XML

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

在模块的 etc/目录下创建一个电子邮件模板配置文件,文件名是email_templates.xml


    
        
    
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"}}  



     
             
             
         
    
             
         
    
        
            
               

{{trans "Billing Info"}}

               

{{var myvar4|raw}}

                         
            
                          {{trans "%customer_name," customer_name=$myvar3}}

            

{{trans "Your custom message."}} {{trans 'Your custom message logging into your account.' account_url=$this.getUrl($store,'admin',[_nosid:1]) |raw}}

        
                          

{{trans 'Your Order #%increment_id' increment_id=$myvar1 |raw}}

            

{{trans 'Placed on %created_at' created_at=$myvar2 |raw}}

        
                         
                                                   {{trans "Item"}}             {{trans "Sku"}}                                                    {{var myvar8|raw}}                                                  {{template config_path="design/email/footer_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

_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

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

getItems() 
?> 

    
    
    
    
    
    
     
    
    
    
    
    
             
             
                 
    
         
         
         
         
             
                     
        getData('entity_id'); ?>
        getData('name'); ?>
        getData('sku'); ?>
        getData('qty'); ?>
        getData('updated_at'); ?>
             
         

如有问题请留言,谢谢。

0