Skip to content

Commit

Permalink
Custom SMTP for Magento 2.0.0 - 2.4.3
Browse files Browse the repository at this point in the history
  • Loading branch information
srenon committed Apr 24, 2024
1 parent b0a9803 commit a6a228c
Show file tree
Hide file tree
Showing 9 changed files with 322 additions and 77 deletions.
71 changes: 32 additions & 39 deletions Block/Adminhtml/ValidateConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,15 @@
namespace MagePal\CustomSmtp\Block\Adminhtml;

use Exception;
use Laminas\Mime\Message as MineMessage;
use Laminas\Mime\Part as MinePart;
use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Validator\EmailAddress;
use MagePal\CustomSmtp\Helper\Data;
use MagePal\CustomSmtp\Model\Email;
use Laminas\Mail\Message;
use Laminas\Mail\Transport\Smtp;
use Laminas\Mail\Transport\SmtpOptions;
use Zend_Mail;
use Zend_Mail_Exception;
use Zend_Mail_Transport_Smtp;
use Zend_Validate_Exception;

class ValidateConfig extends Template
{
Expand Down Expand Up @@ -196,7 +195,7 @@ protected function init()

$this->toAddress = $this->getConfig('email') ? $this->getConfig('email') : $this->getConfig('username');

$this->fromAddress = trim((string) $this->getConfig('from_email'));
$this->fromAddress = trim($this->getConfig('from_email'));

if (!$this->emailAddressValidator->isValid($this->fromAddress)) {
$this->fromAddress = $this->toAddress;
Expand Down Expand Up @@ -246,7 +245,7 @@ public function verify()
/**
* Todo: update to new Zend Framework SMTP
* @return array
* @throws \Exception
* @throws Zend_Mail_Exception
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
protected function validateServerEmailSetting()
Expand All @@ -255,6 +254,7 @@ protected function validateServerEmailSetting()

$username = $this->getConfig('username');
$password = $this->getConfig('password');

$auth = strtolower($this->getConfig('auth'));

//if default view
Expand All @@ -268,31 +268,30 @@ protected function validateServerEmailSetting()
}
}

$name = 'Test from MagePal SMTP';
$from = trim((string) $this->getConfig('from_email'));
$transport = $this->getMailTransportSmtp();

$from = trim($this->getConfig('from_email'));
$from = filter_var($from, FILTER_VALIDATE_EMAIL) ? $from : $username;
$this->fromAddress = filter_var($username, FILTER_VALIDATE_EMAIL) ? $username : $from;
$htmlBody = $this->_email->setTemplateVars(['hash' => $this->hash])->getEmailBody();

$transport = $this->getMailTransportSmtp();

$bodyMessage = new MinePart($htmlBody);
$bodyMessage->type = 'text/html';
//Create email
$name = 'Test from MagePal SMTP';
$mail = new Zend_Mail();
$mail->setFrom($this->fromAddress, $name);
$mail->addTo($this->toAddress, 'MagePal SMTP');
$mail->setSubject('Hello from MagePal SMTP (1 of 2)');

$body = new MineMessage();
$body->addPart($bodyMessage);
$htmlBody = $this->_email->setTemplateVars(['hash' => $this->hash])->getEmailBody();

$message = new Message();
$message->addTo($this->toAddress, 'MagePal SMTP')
->addFrom($this->fromAddress, $name)
->setSubject('Hello from MagePal SMTP (1 of 2)')
->setBody($body)
->setEncoding('UTF-8');
$mail->setBodyHtml($htmlBody);

$result = $this->error();

try {
$transport->send($message);
//only way to prevent zend from giving an error
if (!$mail->send($transport) instanceof Zend_Mail) {
$result = $this->error(true, __('Invalid class, not instance of Zend Mail'));
}
} catch (Exception $e) {
$result = $this->error(true, __($e->getMessage()));
}
Expand All @@ -304,35 +303,29 @@ public function getMailTransportSmtp()
{
$username = $this->getConfig('username');
$password = $this->getConfig('password');

$auth = strtolower($this->getConfig('auth'));

$optionsArray = [
//SMTP server configuration
$smtpHost = $this->getConfig('smtphost');

$smtpConf = [
'name' => $this->getConfig('name'),
'host' => $this->getConfig('smtphost'),
'port' => $this->getConfig('smtpport')
];

if ($auth != 'none') {
$optionsArray['connection_class'] = $auth;
$optionsArray['connection_config'] = [
'username' => $username,
'password' => $password,
];
$smtpConf['auth'] = $auth;
$smtpConf['username'] = $username;
$smtpConf['password'] = $password;
}

$ssl = $this->getConfig('ssl');
if ($ssl != 'none') {
$optionsArray = array_merge_recursive(
['connection_config' => ['ssl' => $ssl]],
$optionsArray
);
$smtpConf['ssl'] = $ssl;
}

$options = new SmtpOptions($optionsArray);
$transport = new Smtp();
$transport->setOptions($options);

return $transport;
return new Zend_Mail_Transport_Smtp($smtpHost, $smtpConf);
}

/**
Expand Down
188 changes: 188 additions & 0 deletions Mail/ZF1/Smtp.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
<?php
/**
* Copyright © MagePal LLC. All rights reserved.
* See COPYING.txt for license details.
* http://www.magepal.com | [email protected]
*/

namespace MagePal\CustomSmtp\Mail\ZF1;

use Exception;
use Magento\Framework\Exception\MailException;
use Magento\Framework\Mail\MessageInterface;
use Magento\Framework\Phrase;
use MagePal\CustomSmtp\Helper\Data;
use MagePal\CustomSmtp\Model\Store;
use Zend_Mail;
use Zend_Mail_Exception;
use Zend_Mail_Transport_Smtp;

/**
* Class Smtp
* For Magento <= 2.2.7
*/

class Smtp extends Zend_Mail_Transport_Smtp
{
/**
* @var Data
*/
protected $dataHelper;

/**
* @var Store
*/
protected $storeModel;

/**
* @param Data $dataHelper
* @param Store $storeModel
*/
public function __construct(
Data $dataHelper,
Store $storeModel
) {
$this->dataHelper = $dataHelper;
$this->storeModel = $storeModel;
}

/**
* @param Data $dataHelper
* @return Smtp
*/
public function setDataHelper(Data $dataHelper)
{
$this->dataHelper = $dataHelper;
return $this;
}

/**
* @param Store $storeModel
* @return Smtp
*/
public function setStoreModel(Store $storeModel)
{
$this->storeModel = $storeModel;
return $this;
}

/**
* @param MessageInterface $message
* @throws MailException
* @throws Zend_Mail_Exception
*/
public function sendSmtpMessage(
MessageInterface $message
) {
$dataHelper = $this->dataHelper;
$dataHelper->setStoreId($this->storeModel->getStoreId());

if ($message instanceof Zend_mail) {
if ($message->getDate() === null) {
$message->setDate();
}
}

//Set reply-to path
switch ($dataHelper->getConfigSetReturnPath()) {
case 1:
$returnPathEmail = $message->getFrom() ?: $this->getFromEmailAddress();
break;
case 2:
$returnPathEmail = $dataHelper->getConfigReturnPathEmail();
break;
default:
$returnPathEmail = null;
break;
}

if ($returnPathEmail !== null && $dataHelper->getConfigSetReturnPath()) {
$message->setReturnPath($returnPathEmail);
}

if ($message->getReplyTo() === null && $dataHelper->getConfigSetReplyTo()) {
$message->setReplyTo($returnPathEmail);
}

//Set from address
switch ($dataHelper->getConfigSetFrom()) {
case 1:
$setFromEmail = $message->getFrom() ?: $this->getFromEmailAddress();
break;
case 2:
$setFromEmail = $dataHelper->getConfigCustomFromEmail();
break;
default:
$setFromEmail = null;
break;
}
if ($setFromEmail !== null && $dataHelper->getConfigSetFrom()) {
$message->clearFrom();
$message->setFrom($setFromEmail);
}

if (!$message->getFrom()) {
$result = $this->storeModel->getFrom();
$message->setFrom($result['email'], $result['name']);
}

//set config
$smtpConf = [
'name' => $dataHelper->getConfigName(),
'port' => $dataHelper->getConfigSmtpPort(),
];

$auth = strtolower($dataHelper->getConfigAuth());
if ($auth != 'none') {
$smtpConf['auth'] = $auth;
$smtpConf['username'] = $dataHelper->getConfigUsername();
$smtpConf['password'] = $dataHelper->getConfigPassword();
}

$ssl = $dataHelper->getConfigSsl();
if ($ssl != 'none') {
$smtpConf['ssl'] = $ssl;
}

$smtpHost = $dataHelper->getConfigSmtpHost();
$this->initialize($smtpHost, $smtpConf);

try {
parent::send($message);
} catch (Exception $e) {
throw new MailException(
new Phrase($e->getMessage()),
$e
);
}
}

/**
* @return string
*/
public function getFromEmailAddress()
{
$result = $this->storeModel->getFrom();
return $result['email'];
}

/**
* @param string $host
* @param array $config
*/
public function initialize($host = '127.0.0.1', array $config = [])
{
if (isset($config['name'])) {
$this->_name = $config['name'];
}
if (isset($config['port'])) {
$this->_port = $config['port'];
}
if (isset($config['auth'])) {
$this->_auth = $config['auth'];
}

$this->_host = $host;
$this->_config = $config;
}
}
24 changes: 10 additions & 14 deletions Mail/Smtp.php → Mail/ZF2/Smtp.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,23 @@
* http://www.magepal.com | [email protected]
*/

namespace MagePal\CustomSmtp\Mail;
namespace MagePal\CustomSmtp\Mail\ZF2;

use Exception;
use Laminas\Mail\AddressList;
use Laminas\Mail\Header\HeaderInterface;
use Laminas\Mail\Message;
use Laminas\Mail\Transport\Smtp as SmtpTransport;
use Laminas\Mail\Transport\SmtpOptions;
use Laminas\Mime\Mime;
use Magento\Framework\Exception\MailException;
use Magento\Framework\Mail\EmailMessageInterface;
use Magento\Framework\Mail\MessageInterface;
use Magento\Framework\Phrase;
use MagePal\CustomSmtp\Helper\Data;
use MagePal\CustomSmtp\Model\Store;
use Zend\Mail\AddressList;
use Zend\Mail\Message;
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Transport\SmtpOptions;

/**
* Class Smtp
* For Magento >= 2.2.8
*/
class Smtp
{
Expand Down Expand Up @@ -97,9 +96,7 @@ protected function convertMessage($message)
}

if (!$zendMessage instanceof Message) {
throw new MailException(
__('Not instance of Message')
);
throw new MailException('Not instance of Message');
}
} catch (Exception $e) {
$zendMessage = Message::fromString($message->getRawMessage());
Expand Down Expand Up @@ -128,7 +125,7 @@ public function sendSmtpMessage(

foreach ($message->getHeaders()->toArray() as $headerKey => $headerValue) {
$mailHeader = $message->getHeaders()->get($headerKey);
if ($mailHeader instanceof HeaderInterface) {
if ($mailHeader instanceof \Zend\Mail\Header\HeaderInterface) {
$this->updateMailHeader($mailHeader);
} elseif ($mailHeader instanceof \ArrayIterator) {
foreach ($mailHeader as $header) {
Expand All @@ -150,7 +147,6 @@ public function sendSmtpMessage(
}

/**
*
* @param Message $message
*/
protected function setSender($message)
Expand Down Expand Up @@ -263,8 +259,8 @@ protected function getSmtpOptions()
*/
public function updateMailHeader($header)
{
if ($header instanceof HeaderInterface) {
if (Mime::isPrintable($header->getFieldValue())) {
if ($header instanceof \Zend\Mail\Header\HeaderInterface) {
if (\Zend\Mime\Mime::isPrintable($header->getFieldValue())) {
$header->setEncoding('ASCII');
} else {
$header->setEncoding('utf-8');
Expand Down
Loading

0 comments on commit a6a228c

Please sign in to comment.