Buy Now

Magento 2- Send mail using your smtp server

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 have a complete module for smtp setup. You can check here SMTP Configurator for Magento2 here.

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 🙂

. . .

Comments (35)

Add Your Comment

  • Muhammad Usman
    helpful..
  • DB
    I’m having trouble after upgrading to 2.1.9. I cant go to 2.2 yet. Should i try this code change?
    • Webkul Support
      yes you can use it with following update
      For magento2 version 2.2.Xyou need to do following updateSetp 1add following method in NameSpaceModuleNameModelTransport.php (Model file)/** * @inheritdoc */public function getMessage() { return $this->message;}Step 2=>update file app/code/NameSpace/ModuleName/etc/di.xml

      Thanks Abhishek

  • Jilco
    After the 2.1.9 upgrade it stopped working, before that it worked like charm! I tried to modify the code but without succes, anyone some code update?
    • Webkul Support
      Hi Jilco,
      tell me your magento updated version. is it 2.2.X?
      Thanks Abhishek
      • Jilco
        Yep! 2.2.1 (latest version)
        • Webkul Support
          For magento2 version 2.2.X
          you need to do following update
          Setp 1
          add following method in NameSpaceModuleNameModelTransport.php (Model file)
          /** * @inheritdoc */
          public function getMessage() {
          return $this->message;
          }
          Step 2=>
          update file app/code/NameSpace/ModuleName/etc/di.xml

          Thanks Abhishek

          • Jilco
            I get the following error and mail is not sending: main.ERROR: Source class “JilcoSMTP_Magento2ModelTransport” for “JilcoSMTP_Magento2ModelTransportInterceptor” generation does not exist.
          • Webkul Support
            just compile magento from CLI or remove generation folder from magneto2 root directory
            Thanks Abhishek
          • Jilco
            Abhishek, i did (again) and stil same error and no mail….
          • Webkul Support
            Did you run “php bin/magento setup:di:compile” from magento root directory and flush cache. If you did it and got same issues then you need to add logger and debug it
            Thanks Abhishek
          • Jilco
            Yep, i ran: php bin/magento cache:flush && php bin/magento setup:upgrade && php bin/magento setup:di:compile && php bin/magento setup:static-content:deploy -f && php bin/magento setup:static-content:deploy nl_NL -f && php bin/magento indexer:reindex
          • Jilco
            How to add logger?
          • Jilco
            by the way, my var/generations is empty…
            Permissions are 777 so they have to be correct
          • Webkul Support
            i am not talking about var/generations . it was in magento 2.1.X version. please delete generated folder from magento root directory in magento 2.2.X.
            Thanks Abhishek
          • Jilco
            i deleted the var/generations folder and did a deploy again, stil the same error…

            main.ERROR: Source class “JilcoSMTP_Magento2ModelTransport” for “JilcoSMTP_Magento2ModelTransportInterceptor” generation does not exist.

          • Webkul Support
            please check my previous response i told you i am not talking about var/generations folder. i am talking about generated folder in magneto root directory http://i.prntscr.com/lfLwZff8SW2YvcCpLg1IKQ.png
            Thanks Abhishek
          • Jilco
            oooo 🙂
            Ik deleted that folder complety and stil the same error. Of course i did a static conten deploy and di
          • Jilco
            Abhishek, does it work in your environment? Have you tested it?
          • Webkul Support
            Jilco, yes it is working well on my end.
            Thanks Abhishek
          • Jilco
            Strange….
            Magento 2.2.1?
          • Jilco
            With tsl => tsl or ssl => tls?

            $smtpConf = [
            ‘auth’ => ‘login’,//auth type
            ‘tsl’ => ‘tsl’,
            ‘port’ => ‘587’,
            ‘username’ => ‘xxxx@xxxxx.xxx’,//smtm user name
            ‘password’ => ‘xxxxxxxxxxxxxx’//smtppassword
            ];

          • Jilco
            yeeeaaaaah, it works!
            Mistake in the DI.xml…..
            Manny thanks!
          • Webkul Support
            Welcome jilco
  • Vipin Surendran
    It should be ‘ssl’ => ‘tls’

    $smtpConf = [
    ‘auth’ => ‘login’,//auth type
    ‘ssl’ => ‘tls’,
    ‘port’ => ‘587’,
    ‘username’ => ‘xxxx@xxxxx.xxx’,//smtm user name
    ‘password’ => ‘xxxxxxxxxxxxxx’//smtppassword
    ];

  • Nazar Korchevskiy
    Thank you!!!
  • Wouter Samaey
    The line ‘tsl’ => ‘tsl’, is wrong and should be ‘ssl’ => ‘tsl’,
  • Wouter Samaey
    This code is fine, but you can only send emails using 1 sender. In a multi-store environment, you’d need multiple username/password combinations for each sender.
  • Sajeed Shaikh
    Hi, I am also new to the magento, so can you just help us out as to where the php module has to be written, we are quite confused regarding this. Thanks.
  • Andrea
    Yeah, thank you for sharing this! It works for me.
    Just a small correction: on line 27 of the Transport class I think it should be ‘tls’ not ‘tsl’.
  • sanchi
    After writing this module , send mail is going to blank page .
    No Logs available @ M2 EE 2.0.5
    I am using AWS SES servics.
  • Mihai
    Hello. Thanks for the tutorial. Can you please tell me where the php file should go. Should I create a new custom module? I’m fairly new to magento. Thanks.
    • Wouter Samaey
      Yes, create a new module.
  • Juan Pedro Barba Soler
    Hello, I have a problem… When I place a new order the SMTP don’t works. I don’t receive any message.
    • webkul
      its hard to predict in this way check your log what you are getting over there ?
  • css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again
    Close