Integrate SMTP to Magento 2
Email communication is an important need for any good e-Commerce store. It increases transparency of the system and reliability of the customers. Many times, Magento store owners have trouble in sending emails. This is because Magento uses PHP mail function by default, so email goes to spam. To overcome this issue SMTP is a prudential solution. You integrate any SMTP provider to Magento 2 store using these steps.
Step 1. Add below code to your plugin’s di.xml.
app/code/Vendor/Module/etc/di.xml
<type name="Magento\Framework\Mail\TransportInterface">
<plugin name="smtp_transport" type="Vendor\Module\Magento\Mail\Transport" sortOrder="1" disabled="false"/>
</type>
Step 2. Create Transport.php and add below code
app/code/Vendor/Module/Magento/Mail/Transport.php
<?phpnamespace Vendor\Module\Magento\Mail;use Magento\Framework\Exception\MailException;
use Magento\Framework\Mail\TransportInterface;
use Magento\Framework\Phrase;
use Magento\Framework\Registry;
use Vendor\Module\Mail\Rse\Mail;
use Psr\Log\LoggerInterface;class Transport{ protected $_storeId;
protected $resourceMail;
protected $registry;
protected $logger;
protected $productMetadata;
public function __construct(
Mail $resourceMail,
Registry $registry,
\Magento\Framework\App\ProductMetadataInterface $productMetadata
){
$this->resourceMail = $resourceMail;
$this->registry = $registry;
$this->productMetadata = $productMetadata;
} public function aroundSendMessage(
TransportInterface $subject,
\Closure $proceed
){
$message = $this->getMessage($subject);
$transport = $this->resourceMail->getTransport();
try {
$transport->send($message);
} catch (\Exception $e) {
throw new MailException(new Phrase($e->getMessage()), $e);
}
} protected function getMessage($transport) {
try {
$reflectionClass = new \ReflectionClass($transport);
$message = $reflectionClass->getProperty('_message');
$message->setAccessible(true);
return $message->getValue($transport);
} catch (\Exception $e) {
return null;
}
}
}
Step 3. Create Mail.php as like below
app/code/Vendor/Module/Mail/Rse/Mail.php
<?phpnamespace Vendor\Module\Mail\Rse;use Magento\Framework\App\ObjectManager;class Mail extends \Zend_Application_Resource_Mail {
protected $_moduleEnable;
protected $_developerMode;
protected $_emailLog = [];
protected $_message;
protected $_smtpOptions = [];
protected $_returnPath = []; public function __construct($options = null) {
parent::__construct($options);
} public function getTransport(){
$this->_smtpOptions = [
'type' => 'smtp',
'host' => '',
'port' => '',
'auth' => '',
'username' => '',
'password' => '',
'ssl' => 'ssl'
]; $this->_transport = null;
$this->setOptions(['transport' => $this->_smtpOptions]);
return $this->init();
}
}
In this file you can write your SMTP credentials like host, port, username, password etc.
After this run below commands to apply the changes,
php bin/magento setup:upgrade
php bin/magento cache:flush