Magento2开发教程十四-发送邮件

定义邮件模板 (<Module>/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="module_hello_email_template" label="Test Mail" file="hello.html" type="html" module="Infinity_Base" area="frontend"/>
</config>

创建邮件模板 (<Module>/view/frontend/email/hello.html)

<!--@subject {{trans "Welcome to %store_name" store_name=$store.getFrontendName()}} @-->
<!--@vars {
"var this.getUrl($store, 'customer/account/')":"Customer Account URL",
"var customer.email":"Customer Email",
"var customer.name":"Customer Name"
} @-->
{{template config_path="design/email/header_template"}}

<p class="greeting">Hello {{trans "%name," name=$name}}</p>

{{template config_path="design/email/footer_template"}}

发出邮件

$templateId = 'module_hello_email_template';
$templateParams = ['name' => 'william'];

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
/* @var \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder */
$transportBuilder = $objectManager->get('Magento\Framework\Mail\Template\TransportBuilder');
/* @var \Magento\Store\Model\StoreManagerInterface $storeManager */
$storeManager = $objectManager->get( 'Magento\Store\Model\StoreManagerInterface' );
/* @var \Magento\Customer\Helper\Session\CurrentCustomer $customer */
$customer = $objectManager->get( '\Magento\Customer\Helper\Session\CurrentCustomer' );

$transportBuilder->setTemplateIdentifier($templateId)
    ->setTemplateOptions(['area' => 'frontend', 'store' => $storeManager->getStore()->getId()])
    ->setTemplateVars($templateParams)
    ->setFrom('general') // sales,support,custom1,custom2
    ->addTo($customer->getCustomer()->getEmail(), $customer->getCustomer()->getFirstname())
    ->getTransport()
    ->sendMessage();

获取邮件模板代码

// template id, 通常在email_templates.xml定义。如果是在后台加的email template,需要换成template的记录ID,例如90
$identifier = 'contact_email_email_template';
/* @var \Magento\Framework\Mail\TemplateInterface $templateFactory */
$templateFactory = $this->_objectManager->create(
    'Magento\Framework\Mail\TemplateInterface',
    ['data' => ['template_id' => $identifier]]
);
// 模板变量,取决于phtml或后台email template的内容
$dataObject = new \Magento\Framework\DataObject();
$dataObject->setData('name', 'william');
// 决定模板变量取值区域,例如像{{layout}}这样的标签,如果取不到值可以试试把area设为frontend
$templateFactory->setOptions([
    'area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE,
    'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID
]);
$templateFactory->setVars(['data' => $dataObject]);
return $templateFactory->processTemplate();

获取所有邮件模板的位置(powershell)

ls -Recurse vendor\magento\*\ | where {$_.Name -eq "email_templates.xml"} | foreach {
    $modulePath = $_.Directory.Parent.FullName
    $emailTemplatesXml = (get-content $_)
    $emailTemplatesXml.config.template | foreach {
        $file = $_.GetAttribute("file")
        $area = $_.GetAttribute("area").toString()
        write-host "(Label):"$_.GetAttribute("label").toString()    "(ID):"$_.GetAttribute("id").toString()    "(file):"$modulePath\view\$area\email\$file
    }
}

关于模板变量

虽然通过email_templates.xml找到邮件模板很容易,但模板中使用的变量是PHP端提供的,模板变量只能在发送邮件的时候定义,所以如果要调整模板变量往往不太好找。以下列出自带组件含模板变量定义部分的代码位置

vendor/magento/module-sales/Model/Order/Email/Sender/*.php
vendor/magento/module-customer/Model/EmailNotification.php
vendor/magento/module-send-friend/Model/SendFriend.php

有趣的是order相关的email有event可以追加模板变量,例如email_order_set_template_vars_before,但并不是所有官方开发的邮件变量都有event可用。

官方的邮件变量定义代码都在Model里,但第三方组件就未必。其实也并不难找,只要对组件全代码搜索->setTemplateVars(,就可以很容易找到。

其他方式

Controller文件,也可改为Model或Helper

<?php
namespace Yourmodule\Smtp\Controller\Index\Index;
/**
 * Class Index
 * @package Yourmodule\Smtp\Controller\Adminhtml\Index
 */
class Index extends \Magento\Backend\App\Action
{
    /**
     * Authorization level of a basic admin session
     *
     * @see _isAllowed()
     */
    const ADMIN_RESOURCE = 'Yourmodule_Smtp::smtp';
    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;
    /**
     * @var \Magento\Framework\Json\Helper\Data
     */
    protected $jsonHelper;
    /**
     * @var \Psr\Log\LoggerInterface
     */
    private $logger;
    /**
     * @var \Magento\Framework\Encryption\EncryptorInterface
     */
    private $encryptor;
    /**
     * @var \Yourmodule\Smtp\Helper\Data
     */
    private $smtpDataHelper;
    /**
     * Constructor
     *
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\Json\Helper\Data $jsonHelper
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Magento\Framework\Json\Helper\Data $jsonHelper,
        \Magento\Framework\Encryption\EncryptorInterface $encryptor,
        \Psr\Log\LoggerInterface $logger,
        \Yourmodule\Smtp\Helper\Data $smtpDataHelper
    )
    {
        $this->resultPageFactory = $resultPageFactory;
        $this->jsonHelper        = $jsonHelper;
        $this->logger            = $logger;
        $this->encryptor         = $encryptor;
        $this->smtpDataHelper    = $smtpDataHelper;
        parent::__construct($context);
    }
    /**
     * Execute view action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $params           = $this->getRequest()->getParams();
        $result           = [];
        $result['status'] = false;
        if ($params && $params['email']) {
            $config = [];
            $host   = $params['host'];
            if ($params['protocol']) {
                $config['ssl'] = $params['protocol'];
            }
            if ($params['port']) {
                $config['port'] = $params['port'];
            }
            $config['auth']     = $params['authentication'];
            $config['username'] = $params['username'];
            if ($params['password'] == '******') {
                $config['password'] = $this->encryptor->decrypt($this->smtpDataHelper->getConfig('configuration_option', 'password'));
            } else {
                $config['password'] = $params['password'];
            }
            $transport = new \Zend_Mail_Transport_Smtp($host, $config);
            $mail      = new \Zend_Mail();
            if ($params['username']) {
                $mail->setFrom($config['username']);
            }
            $mail->addTo($params['email']);
            $mail->setSubject(__('TEST EMAIL from Custom SMTP'));
            $body = "Your store has been connected with a custom SMTP successfully.";
            $mail->setBodyText($body);
            try {
                $mail->send($transport);
                $result['status']  = true;
                $result['content'] = __('Sent successfully! Please check your email box.');
            } catch (\Exception $e) {
                $result['content'] = $e->getMessage();
                $this->logger->critical($e);
            }
        } else {
            $result['content'] = __('Test Error');
        }
        return $this->jsonResponse($result);
    }
    /**
     * Create json response
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function jsonResponse($response = '')
    {
        return $this->getResponse()->representJson(
            $this->jsonHelper->jsonEncode($response)
        );
    }
}

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论