Magento 2 使用 Smtp 发送邮件 Magento 2- Send Mail Using Your Smtp Server

7天成为Magento系统架构师,现在开始学习Magento全栈开发!

《Magento2.X企业级开发实战》

Here we learn how to send mail using our smtp detail in magento2

For this we need to override mageto \Magento\Framework\Mail\Transport class by your custom model class

We can do it in two step

1# For override we need to write code in module di.xml file at location app/code/NameSpace/ModuleName/etc

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <!-- for override magento default Transport class with our custom module model-->
    <preference for="\Magento\Framework\Mail\Transport" type="NameSpace\ModuleName\Model\Transport"/>
</config>

2# Now we’ll define our Transport model in our custom module

<?php
/**
 * Mail Transport
 */
namespace NameSpace\ModuleName\Model;
 
class Transport extends \Zend_Mail_Transport_Smtp implements \Magento\Framework\Mail\TransportInterface
{
    /**
     * @var \Magento\Framework\Mail\MessageInterface
     */
    protected $_message;
 
    /**
     * @param MessageInterface $message
     * @param null $parameters
     * @throws \InvalidArgumentException
     */
    public function __construct(\Magento\Framework\Mail\MessageInterface $message)
    {
        if (!$message instanceof \Zend_Mail) {
            throw new \InvalidArgumentException('The message should be an instance of \Zend_Mail');
        }
         $smtpHost= 'xxx.xxxx.xxx';//your smtp host  ';
         $smtpConf = [
            'auth' => 'login',//auth type
            'tsl' => 'tsl', 
            'port' => '587',
            'username' => 'xxxx@xxxxx.xxx',//smtm user name
            'password' => 'xxxxxxxxxxxxxx'//smtppassword 
         ];
 
        parent::__construct($smtpHost, $smtpConf);
        $this->_message = $message;
    }
 
    /**
     * Send a mail using this transport
     * @return void
     * @throws \Magento\Framework\Exception\MailException
     */
    public function sendMessage()
    {
        try {
            parent::send($this->_message);
        } catch (\Exception $e) {
            throw new \Magento\Framework\Exception\MailException(new \Magento\Framework\Phrase($e->getMessage()), $e);
        }
    }
}

Now all mail goes from your magento 2 instance using your smtp server

如无特殊说明或标注,任何个人或组织,复制、转载、采集本站内容请注明:
本文来源于:【Magento中文网】,并添加本文地址链接。
如未按上述操作复制或转载,本站有权追究法律责任。
若本站内容侵犯了原著者的合法权益,可联系我们进行处理。