Commit 1c268750 authored by Stefan Galinski's avatar Stefan Galinski 🎮
Browse files

[BUGFIX] Handle errors while sending mails correctly without exceptions,...

[BUGFIX] Handle errors while sending mails correctly without exceptions, Visualize errors inside the backend
parent 5f6f3141
......@@ -27,11 +27,11 @@ namespace SGalinski\SgMail\Command;
use SGalinski\SgMail\Domain\Repository\MailRepository;
use SGalinski\SgMail\Service\MailTemplateService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use Symfony\Component\Console\Command\Command;
use TYPO3\CMS\Core\Utility\VersionNumberUtility;
use TYPO3\CMS\Extbase\Object\Exception;
use TYPO3\CMS\Extbase\Object\ObjectManager;
......
......@@ -22,6 +22,7 @@
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
namespace SGalinski\SgMail\Service;
use DateTime;
......@@ -31,9 +32,7 @@ use SGalinski\SgMail\Domain\Repository\LayoutRepository;
use SGalinski\SgMail\Domain\Repository\MailRepository;
use SGalinski\SgMail\Domain\Repository\TemplateRepository;
use Swift_Attachment;
use Symfony\Component\Mailer\Exception\TransportException;
use TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException;
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Mail\MailMessage;
use TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException;
use TYPO3\CMS\Core\Resource\File;
......@@ -220,7 +219,9 @@ class MailTemplateService implements SingletonInterface {
* @param array $markerLabels
* @throws Exception
*/
public function __construct(string $templateName = '', string $extensionKey = '', array $markers = [], array $markerLabels = []) {
public function __construct(
string $templateName = '', string $extensionKey = '', array $markers = [], array $markerLabels = []
) {
$this->templateName = $templateName;
$this->extensionKey = $extensionKey;
$this->markers = $markers;
......@@ -239,10 +240,12 @@ class MailTemplateService implements SingletonInterface {
// use defaultMailFromAddress if it is provided in LocalConfiguration.php; use the sg_mail TS setting as fallback
if (filter_var($GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromAddress'], FILTER_VALIDATE_EMAIL)) {
$this->fromAddress = $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromAddress'];
} else if (!filter_var($tsSettings['mail']['default']['from'], FILTER_VALIDATE_EMAIL)) {
$this->fromAddress = 'noreply@example.org';
} else {
$this->fromAddress = $tsSettings['mail']['default']['from'];
if (!filter_var($tsSettings['mail']['default']['from'], FILTER_VALIDATE_EMAIL)) {
$this->fromAddress = 'noreply@example.org';
} else {
$this->fromAddress = $tsSettings['mail']['default']['from'];
}
}
if ($GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromName']) {
......@@ -275,7 +278,8 @@ class MailTemplateService implements SingletonInterface {
* @param string $extensionKey
* @return array
*/
public static function getDefaultTemplateMarker(string $translationKey, array $marker, $extensionKey = 'sg_mail'): array {
public static function getDefaultTemplateMarker(string $translationKey, array $marker, $extensionKey = 'sg_mail'
): array {
$languagePath = 'LLL:EXT:' . $extensionKey . '/Resources/Private/Language/locallang.xlf:' . $translationKey;
// Need the key for translations
if (trim($extensionKey) === '') {
......@@ -325,12 +329,12 @@ class MailTemplateService implements SingletonInterface {
$coreFileReferenceMailFile = GeneralUtility::makeInstance(ResourceFactory::class)
->createFileReferenceObject(
[
'uid_local' => $file->getUid(),
'table_local' => 'sys_file',
'uid' => uniqid('NEW_MAIL', TRUE)
]
);
[
'uid_local' => $file->getUid(),
'table_local' => 'sys_file',
'uid' => uniqid('NEW_MAIL', TRUE)
]
);
$newFileReference = GeneralUtility::makeInstance(FileReference::class);
$newFileReference->setOriginalResource($coreFileReferenceMailFile);
......@@ -466,7 +470,7 @@ class MailTemplateService implements SingletonInterface {
$template = $this->getTemplateRepository()->findByTemplateProperties(
$this->extensionKey, $this->templateName, $fallbackLanguages, $this->pid
)->getFirst();
} elseif($template === NULL) {
} elseif ($template === NULL) {
$templateArray = $this->registerService->findTemplate(
$this->extensionKey,
$this->templateName,
......@@ -546,8 +550,6 @@ class MailTemplateService implements SingletonInterface {
return $fromMail;
}
/**
* Get the default content for this template
*
......@@ -841,12 +843,12 @@ class MailTemplateService implements SingletonInterface {
if ($originalResource instanceof CoreFileReference) {
$coreFileReferenceMailFile = GeneralUtility::makeInstance(ResourceFactory::class)
->createFileReferenceObject(
[
'uid_local' => $originalResource->getOriginalFile()->getUid(),
'table_local' => 'sys_file',
'uid' => uniqid('NEW_MAIL', TRUE)
]
);
[
'uid_local' => $originalResource->getOriginalFile()->getUid(),
'table_local' => 'sys_file',
'uid' => uniqid('NEW_MAIL', TRUE)
]
);
$newFileReference = GeneralUtility::makeInstance(FileReference::class);
$newFileReference->setOriginalResource($coreFileReferenceMailFile);
$mail->addAttachment($newFileReference);
......@@ -917,7 +919,9 @@ class MailTemplateService implements SingletonInterface {
* @param string $htmlBody
* @param string $plainBody
*/
protected static function addBodyToMailMessage(MailMessage $mailMessage, string $htmlBody = '', string $plainBody = ''): void {
protected static function addBodyToMailMessage(
MailMessage $mailMessage, string $htmlBody = '', string $plainBody = ''
): void {
if (version_compare(VersionNumberUtility::getCurrentTypo3Version(), '10.4.0', '<')) {
$mailMessage->setBody($htmlBody, 'text/html');
$mailMessage->addPart($plainBody, 'text/plain');
......@@ -929,6 +933,7 @@ class MailTemplateService implements SingletonInterface {
/**
* Attach a file
*
* @param MailMessage $mailMessage
* @param FileInterface $file
*/
......@@ -945,6 +950,7 @@ class MailTemplateService implements SingletonInterface {
}
/**
* Sends the given mail objects
*
* @param Mail[] $mails
* @throws Exception
......@@ -952,88 +958,94 @@ class MailTemplateService implements SingletonInterface {
* @throws UnknownObjectException
*/
public function sendMailsFromQueue(array $mails): void {
$mailRepository = $this->getMailRepository();
foreach ($mails as $mail) {
$mailMessage = GeneralUtility::makeInstance(MailMessage::class);
$toAddresses = trim($mail->getToAddress());
$addressesArray = GeneralUtility::trimExplode(',', $mail->getToAddress(), TRUE);
if (count($addressesArray) > 1) {
$toAddresses = $addressesArray;
}
try {
/** @var MailMessage $mailMessage */
$mailMessage = GeneralUtility::makeInstance(MailMessage::class);
$toAddresses = trim($mail->getToAddress());
$addressesArray = GeneralUtility::trimExplode(',', $mail->getToAddress(), TRUE);
if (count($addressesArray) > 1) {
$toAddresses = $addressesArray;
}
if ($toAddresses === '') {
if (\filter_var($GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromAddress'], FILTER_VALIDATE_EMAIL)) {
$mailMessage->setTo($GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromAddress']);
if ($toAddresses === '') {
$isValidMailAddress = \filter_var(
$GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromAddress'], FILTER_VALIDATE_EMAIL
);
if ($isValidMailAddress) {
$mailMessage->setTo($GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromAddress']);
} else {
$mail->setStatus(Mail::STATUS_ERROR);
$mail->setErrorMessage(LocalizationUtility::translate('error.noValidToAddress', 'sg_mail'));
continue;
}
} else {
$mail->setStatus(Mail::STATUS_ERROR);
$mail->setErrorMessage(LocalizationUtility::translate('error.noValidToAddress', 'sg_mail'));
continue;
$mailMessage->setTo($toAddresses);
}
} else {
$mailMessage->setTo($toAddresses);
}
$mailMessage->setFrom($mail->getFromAddress(), $mail->getFromName());
$mailMessage->setCc(
GeneralUtility::trimExplode(',', $mail->getCcAddresses(), TRUE)
);
$mailMessage->setBcc(
GeneralUtility::trimExplode(',', $mail->getBccAddresses(), TRUE)
);
$mailMessage->setSubject($mail->getMailSubject());
$plaintextService = GeneralUtility::makeInstance(PlaintextService::class);
$plaintextBody = $plaintextService->makePlain($mail->getMailBody());
self::addBodyToMailMessage($mailMessage, $mail->getMailBody(), $plaintextBody);
$mailMessage->setFrom($mail->getFromAddress(), $mail->getFromName());
$mailMessage->setCc(
GeneralUtility::trimExplode(',', $mail->getCcAddresses(), TRUE)
);
$mailMessage->setBcc(
GeneralUtility::trimExplode(',', $mail->getBccAddresses(), TRUE)
);
$mailMessage->setSubject($mail->getMailSubject());
$plaintextService = GeneralUtility::makeInstance(PlaintextService::class);
$plaintextBody = $plaintextService->makePlain($mail->getMailBody());
self::addBodyToMailMessage($mailMessage, $mail->getMailBody(), $plaintextBody);
if ($mail->getBccAddresses()) {
$mailMessage->setBcc(GeneralUtility::trimExplode(',', $mail->getBccAddresses()));
}
if ($mail->getBccAddresses()) {
$mailMessage->setBcc(GeneralUtility::trimExplode(',', $mail->getBccAddresses()));
}
if ($mail->getCcAddresses()) {
$mailMessage->setCc(GeneralUtility::trimExplode(',', $mail->getCcAddresses()));
}
if ($mail->getCcAddresses()) {
$mailMessage->setCc(GeneralUtility::trimExplode(',', $mail->getCcAddresses()));
}
if ($mail->getReplyTo()) {
$mailMessage->setReplyTo($mail->getReplyTo());
}
if ($mail->getReplyTo()) {
$mailMessage->setReplyTo($mail->getReplyTo());
}
$attachments = $mail->getAttachments();
if ($attachments->count() > 0) {
foreach ($attachments as $attachment) {
/**
* @var FileReference $attachment
*/
$originalResource = $attachment->getOriginalResource();
if ($originalResource === NULL) {
continue;
$attachments = $mail->getAttachments();
if ($attachments->count() > 0) {
foreach ($attachments as $attachment) {
/**
* @var FileReference $attachment
*/
$originalResource = $attachment->getOriginalResource();
if ($originalResource === NULL) {
continue;
}
$file = $originalResource->getOriginalFile();
self::attachToMailMessage($mailMessage, $file);
}
}
$file = $originalResource->getOriginalFile();
self::attachToMailMessage($mailMessage, $file);
$dateTime = new DateTime();
if ($mail->getSendingTime() === 0) {
$mail->setSendingTime($dateTime->getTimestamp());
}
}
$dateTime = new DateTime();
if ($mail->getSendingTime() === 0) {
$mail->setSendingTime($dateTime->getTimestamp());
}
$mail->setLastSendingTime($dateTime->getTimestamp());
$mail->setLastSendingTime($dateTime->getTimestamp());
try {
$success = $mailMessage->send();
if (!$success) {
$mail->setStatus(Mail::STATUS_ERROR);
$mail->setErrorMessage(LocalizationUtility::translate('error.mailsending', 'sg_mail'));
}
$mail->setStatus(Mail::STATUS_SENT);
} catch (TransportException $exception) {
} catch (\Exception $exception) {
$mail->setStatus(Mail::STATUS_ERROR);
$mail->setErrorMessage($exception->getMessage());
}
$this->getMailRepository()->update($mail);
$mailRepository->update($mail);
}
$this->getMailRepository()->persist();
$mailRepository->persist();
}
/**
......
......@@ -73,7 +73,7 @@
format="d.m.Y H:i">{mail.last_sending_time}</f:format.date></span>
</f:then>
<f:else>
<f:translate key="backend.not_sent"/>
<f:translate key="backend.not_sent"/> ({mail.status})
</f:else>
</f:if>
</td>
......@@ -102,6 +102,15 @@
<core:icon identifier="actions-view-page"/>
</button>
</td>
</tr>
<f:if condition="{mail.error_message}">
<tr>
<td style="border-top: none;">&nbsp;</td>
<td colspan="5" style="border-top: none;">
<strong>{mail.error_message}</strong>
</td>
</tr>
</f:if>
</f:for>
</tbody>
</sgm:backend.widget.paginate>
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment