Skip to content

Commit

Permalink
Improve send test email & add ignore_log/force_sent param
Browse files Browse the repository at this point in the history
  • Loading branch information
haitv282 committed Jun 7, 2018
1 parent 74f8861 commit 4d0fa0c
Show file tree
Hide file tree
Showing 7 changed files with 151 additions and 104 deletions.
115 changes: 47 additions & 68 deletions Controller/Adminhtml/Smtp/Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\Framework\Json\Helper\Data;
use Magento\Framework\Mail\Template\SenderResolverInterface;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Area;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Store\Model\Store;
use Mageplaza\Smtp\Helper\Data as SmtpData;
use Mageplaza\Smtp\Mail\Rse\Mail;
use Psr\Log\LoggerInterface;

/**
Expand All @@ -43,118 +43,99 @@ class Test extends Action
*/
const ADMIN_RESOURCE = 'Mageplaza_Smtp::smtp';

/**
* @var \Magento\Framework\View\Result\PageFactory
*/
protected $resultPageFactory;

/**
* @var \Magento\Framework\Json\Helper\Data
*/
protected $jsonHelper;

/**
* @var \Psr\Log\LoggerInterface
*/
protected $logger;

/**
* @var \Magento\Framework\Encryption\EncryptorInterface
* @var \Mageplaza\Smtp\Helper\Data
*/
protected $encryptor;
protected $smtpDataHelper;

/**
* Sender resolver
*
* @var \Magento\Framework\Mail\Template\SenderResolverInterface
* @var Mail
*/
protected $_senderResolver;
protected $mailResource;

/**
* @var \Mageplaza\Smtp\Helper\Data
* @var TransportBuilder
*/
protected $smtpDataHelper;
protected $_transportBuilder;

/**
* Index constructor.
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
* @param \Magento\Framework\Json\Helper\Data $jsonHelper
* @param \Magento\Framework\Encryption\EncryptorInterface $encryptor
* @param \Psr\Log\LoggerInterface $logger
* @param \Magento\Framework\Mail\Template\SenderResolverInterface $senderResolver
* @param \Mageplaza\Smtp\Helper\Data $smtpDataHelper
* Test constructor.
* @param Context $context
* @param LoggerInterface $logger
* @param SmtpData $smtpDataHelper
* @param Mail $mailResource
* @param TransportBuilder $transportBuilder
*/
public function __construct(
Context $context,
PageFactory $resultPageFactory,
Data $jsonHelper,
EncryptorInterface $encryptor,
LoggerInterface $logger,
SenderResolverInterface $senderResolver,
SmtpData $smtpDataHelper
SmtpData $smtpDataHelper,
Mail $mailResource,
TransportBuilder $transportBuilder
)
{
$this->resultPageFactory = $resultPageFactory;
$this->jsonHelper = $jsonHelper;
$this->logger = $logger;
$this->encryptor = $encryptor;
$this->_senderResolver = $senderResolver;
$this->smtpDataHelper = $smtpDataHelper;
$this->mailResource = $mailResource;
$this->_transportBuilder = $transportBuilder;

parent::__construct($context);
}

/**
* @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface
* @throws \Magento\Framework\Exception\MailException
* @throws \Zend_Mail_Exception
*/
public function execute()
{
$result = ['status' => false];

$params = $this->getRequest()->getParams();
if ($params && $params['to']) {
$config = [];
$host = $params['host'];
$config = [
'type' => 'smtp',
'host' => $params['host'],
'auth' => $params['authentication'],
'username' => $params['username'],
'ignore_log' => true,
'force_sent' => true
];

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->smtpDataHelper->getTestPassword(true);
$config['password'] = $this->smtpDataHelper->getPassword();
} else {
$config['password'] = $params['password'];
}

$transport = new \Zend_Mail_Transport_Smtp($host, $config);
$mail = new \Zend_Mail();

if ($params['from']) {
$result = $this->_senderResolver->resolve($params['from']);
$mail->setFrom($result['email'], $result['name']);
} else {
$mail->setFrom($config['username']);
}

if ($params['returnpath']) {
$mail->setReturnPath($params['returnpath']);
$config['return_path'] = $params['returnpath'];
}

$mail->addTo($params['to']);
$mail->setSubject(__('TEST EMAIL from Custom SMTP'));
$mail->setBodyText("Your store has been connected with a custom SMTP successfully. Now you can Save Config and use this connection. \n\n
Sent via SMTP by https://www.mageplaza.com");
$this->mailResource->setSmtpOptions(Store::DEFAULT_STORE_ID, $config);

$this->_transportBuilder
->setTemplateIdentifier('mpsmtp_test_email_template')
->setTemplateOptions(['area' => Area::AREA_FRONTEND, 'store' => Store::DEFAULT_STORE_ID])
->setTemplateVars([])
->setFrom(isset($params['from']) ? $params['from'] : $config['username'])
->addTo($params['to']);

try {
$mail->send($transport);
$result['status'] = true;
$result['content'] = __('Sent successfully! Please check your email box.');
$this->_transportBuilder->getTransport()->sendMessage();

$result = [
'status' => true,
'content' => __('Sent successfully! Please check your email box.')
];
} catch (\Exception $e) {
$result['content'] = $e->getMessage();
$this->logger->critical($e);
Expand All @@ -163,8 +144,6 @@ public function execute()
$result['content'] = __('Test Error');
}

return $this->getResponse()->representJson(
$this->jsonHelper->jsonEncode($result)
);
return $this->getResponse()->representJson(SmtpData::jsonEncode($result));
}
}
11 changes: 6 additions & 5 deletions Helper/Data.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,21 +59,22 @@ public function getDeveloperConfig($code = '', $storeId = null)
}

/**
* @param null $storeId
* @param bool $decrypt
* @return array|mixed
* @return array|mixed|string
*/
public function getTestPassword($decrypt = false)
public function getPassword($storeId = null, $decrypt = true)
{
if ($storeCode = $this->_request->getParam('store')) {
$password = $this->getSmtpConfig('password', $storeCode);
if ($storeId || $storeId = $this->_request->getParam('store')) {
$password = $this->getSmtpConfig('password', $storeId);
} else if ($websiteCode = $this->_request->getParam('website')) {
$passwordPath = self::CONFIG_MODULE_PATH . '/' . self::CONFIG_GROUP_SMTP . '/password';
$password = $this->getConfigValue($passwordPath, $websiteCode, ScopeInterface::SCOPE_WEBSITE);
} else {
$password = $this->getSmtpConfig('password');
}

if($decrypt){
if ($decrypt) {
/** @var \Magento\Framework\Encryption\EncryptorInterface $encryptor */
$encryptor = $this->getObject(\Magento\Framework\Encryption\EncryptorInterface::class);

Expand Down
57 changes: 44 additions & 13 deletions Mail/Rse/Mail.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
namespace Mageplaza\Smtp\Mail\Rse;

use Magento\Framework\App\ObjectManager;
use Magento\Framework\Encryption\EncryptorInterface;
use Mageplaza\Smtp\Helper\Data;

/**
Expand All @@ -36,11 +35,6 @@ class Mail extends \Zend_Application_Resource_Mail
*/
protected $smtpHelper;

/**
* @var EncryptorInterface
*/
protected $encryptor;

/**
* @var boolean is module enable
*/
Expand All @@ -54,7 +48,7 @@ class Mail extends \Zend_Application_Resource_Mail
/**
* @var boolean is enable email log
*/
protected $_emailLog;
protected $_emailLog = [];

/**
* @var string message body email
Expand All @@ -64,7 +58,12 @@ class Mail extends \Zend_Application_Resource_Mail
/**
* @var array option by storeid
*/
protected $_smtpOptions;
protected $_smtpOptions = [];

/**
* @var array
*/
protected $_returnPath = [];

/**
* Mail constructor.
Expand All @@ -73,11 +72,39 @@ class Mail extends \Zend_Application_Resource_Mail
public function __construct($options = null)
{
$this->smtpHelper = ObjectManager::getInstance()->get(Data::class);
$this->encryptor = ObjectManager::getInstance()->get(EncryptorInterface::class);

parent::__construct($options);
}

/**
* @param $storeId
* @param array $options
* @return $this
*/
public function setSmtpOptions($storeId, $options = [])
{
if (isset($options['return_path'])) {
$this->_returnPath[$storeId] = $options['return_path'];
unset($options['return_path']);
}

if (isset($options['ignore_log']) && $options['ignore_log']) {
$this->_emailLog[$storeId] = false;
unset($options['ignore_log']);
}

if (isset($options['force_sent']) && $options['force_sent']) {
$this->_moduleEnable[$storeId] = true;
unset($options['force_sent']);
}

if (sizeof($options)) {
$this->_smtpOptions[$storeId] = $options;
}

return $this;
}

/**
* @param $storeId
* @return mixed|null|\Zend_Mail_Transport_Abstract
Expand All @@ -92,10 +119,10 @@ public function getTransport($storeId)
'port' => isset($configData['port']) ? $configData['port'] : '',
'auth' => isset($configData['authentication']) ? $configData['authentication'] : '',
'username' => isset($configData['username']) ? $configData['username'] : '',
'password' => isset($configData['password']) ? $this->encryptor->decrypt($configData['password']) : '',
'password' => $this->smtpHelper->getPassword($storeId)
];

if(isset($configData['protocol'])){
if (isset($configData['protocol'])) {
$this->_smtpOptions[$storeId]['ssl'] = $configData['protocol'];
}
}
Expand All @@ -113,8 +140,12 @@ public function getTransport($storeId)
*/
public function processMessage($message, $storeId)
{
if ($returnPath = $this->smtpHelper->getSmtpConfig('return_path_email', $storeId)) {
$message->setReturnPath($returnPath);
if (!isset($this->_returnPath[$storeId])) {
$this->_returnPath[$storeId] = $this->smtpHelper->getSmtpConfig('return_path_email', $storeId);
}

if ($this->_returnPath[$storeId]) {
$message->setReturnPath($this->_returnPath[$storeId]);
}

return $message;
Expand Down
14 changes: 11 additions & 3 deletions Mail/Transport.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
use Mageplaza\Smtp\Helper\Data;
use Mageplaza\Smtp\Mail\Rse\Mail;
use Mageplaza\Smtp\Model\LogFactory;
use Psr\Log\LoggerInterface;

/**
* Class Transport
Expand Down Expand Up @@ -60,24 +61,32 @@ class Transport
*/
protected $helper;

/**
* @var LoggerInterface
*/
protected $logger;

/**
* Transport constructor.
* @param Mail $resourceMail
* @param LogFactory $logFactory
* @param Registry $registry
* @param Data $helper
* @param LoggerInterface $logger
*/
public function __construct(
Mail $resourceMail,
LogFactory $logFactory,
Registry $registry,
Data $helper
Data $helper,
LoggerInterface $logger
)
{
$this->resourceMail = $resourceMail;
$this->logFactory = $logFactory;
$this->registry = $registry;
$this->helper = $helper;
$this->logger = $logger;
}

/**
Expand Down Expand Up @@ -137,7 +146,6 @@ protected function getMessage($transport)
*
* @param $message
* @param bool $status
* @throws \Magento\Framework\Exception\MailException
*/
protected function emailLog($message, $status = true)
{
Expand All @@ -147,7 +155,7 @@ protected function emailLog($message, $status = true)
try {
$log->saveLog($message, $status);
} catch (\Exception $e) {
throw new MailException(new Phrase($e->getMessage()), $e);
$this->logger->critical($e->getMessage());
}
}
}
Expand Down
Loading

0 comments on commit 4d0fa0c

Please sign in to comment.