Skip to content

Instantly share code, notes, and snippets.

@tboock
Forked from bwaidelich/EmailService.php
Last active August 29, 2015 14:15
Show Gist options
  • Save tboock/74bb11e2003ef9e9ed6f to your computer and use it in GitHub Desktop.
Save tboock/74bb11e2003ef9e9ed6f to your computer and use it in GitHub Desktop.
TYPO3 Flow EmailService
<?php
namespace Vendor\MyPackage\Mail;
use TYPO3\Flow\Annotations as Flow;
use TYPO3\Flow\Configuration\ConfigurationManager;
use TYPO3\Flow\Log\SystemLoggerInterface;
use TYPO3\Flow\Mvc\Routing\Router;
use TYPO3\Flow\Mvc\Routing\RouterInterface;
use TYPO3\Flow\Reflection\ObjectAccess;
use TYPO3\Fluid\View\StandaloneView;
use TYPO3\SwiftMailer\Message;
/**
* @Flow\Scope("singleton")
*/
class MailService {
/**
* @var SystemLoggerInterface
* @Flow\Inject
*/
protected $systemLogger = NULL;
/**
* @var ConfigurationManager
* @Flow\Inject
*/
protected $configurationManager = NULL;
/**
* @var RouterInterface
* @Flow\Inject
*/
protected $router = NULL;
/**
* @var array
* @Flow\Inject(setting="mail")
*/
protected $settings = [];
/**
* Initializes the service.
*/
public function initializeObject() {
$this->initializeRouter();
}
/**
* Initializes the injected router-object.
*
* Manual initialization is required when building links in CLI mode.
*/
protected function initializeRouter() {
// Note that setRoutesConfiguration() is not defined in the interface.
if ($this->router instanceof Router || ObjectAccess::isPropertySettable($this->router, 'routesConfiguration')) {
$routesConfiguration = $this->configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_ROUTES);
// Calls the setter method, if possible.
ObjectAccess::setProperty($this->router, 'routesConfiguration', $routesConfiguration);
}
}
/**
* @param Recipient $recipient recipient of the mail
* @param string $subject subject of the mail
* @param string $packageKey the name of the package which contains the template
* @param string $templateIdentifier name of the mail template to use @see renderMailBody()
* @param array $variables variables that will be available in the mail template. in the format array('<key>' => '<value>', ....)
* @return boolean TRUE on success, otherwise FALSE
*/
public function sendTemplateBasedMail(Recipient $recipient, $subject, $packageKey, $templateIdentifier, array $variables = []) {
$plaintextBody = $this->renderPlaintextMailBody($packageKey, $templateIdentifier, $variables);
$htmlBody = $this->renderHtmlMailBody($packageKey, $templateIdentifier, $variables);
$mail = $this->createMail($recipient, $subject, $plaintextBody, $htmlBody);
return $this->sendMail($mail);
}
/**
* @param string $packageKey
* @param string $templateIdentifier
* @param array $variables
* @return string
*/
protected function renderPlaintextMailBody($packageKey, $templateIdentifier, array $variables) {
return $this->renderMailBody($packageKey, $templateIdentifier, $variables, 'txt');
}
/**
* @param string $packageKey
* @param string $templateIdentifier
* @param array $variables
* @return string
*/
protected function renderHtmlMailBody($packageKey, $templateIdentifier, array $variables) {
return $this->renderMailBody($packageKey, $templateIdentifier, $variables, 'html');
}
/**
* @param string $packageKey
* @param string $templateIdentifier
* @param array $variables
* @param string $format
* @return string
*/
protected function renderMailBody($packageKey, $templateIdentifier, array $variables, $format) {
$standaloneView = new StandaloneView();
$request = $standaloneView->getRequest();
$request->setControllerPackageKey($packageKey);
$templateFilePath = 'resource://' . $packageKey . '/Private/Templates/Mail/' . $templateIdentifier . '.' . $format;
$standaloneView->setTemplatePathAndFilename($templateFilePath);
$standaloneView->assignMultiple($variables);
return $standaloneView->render();
}
/**
* @param Recipient $recipient
* @param string $subject
* @param string $plaintextBody
* @param string $htmlBody
* @return Message
*/
protected function createMail(Recipient $recipient, $subject, $plaintextBody, $htmlBody) {
$mail = new Message();
$mail->setFrom([
$this->settings['sender']['emailAddress'] => $this->settings['sender']['name']
])
->setTo($recipient->toArray())
->setSubject($subject)
->setBody($plaintextBody);
$mail->addPart($htmlBody, 'text/html');
return $mail;
}
/**
* Sends the mail and creates a system logger entry on failure.
*
* @param Message $mail
* @return boolean TRUE on success, otherwise FALSE
*/
protected function sendMail(Message $mail) {
$numberOfRecipients = 0;
$exception = NULL;
try {
$numberOfRecipients = $mail->send();
} catch (\Exception $e) {
$exception = $e;
}
if ($numberOfRecipients === 0) {
$this->logDeliveryFailure($mail, $exception);
return FALSE;
}
return TRUE;
}
/**
* Logs a delivery failure.
*
* @param Message $mail
* @param \Exception|NULL $exception
*/
protected function logDeliveryFailure(Message $mail, \Exception $exception = NULL) {
$additionalData = [
'subject' => $mail->getSubject(),
'id' => (string) $mail->getHeaders()->get('Message-ID')
];
if ($exception !== NULL) {
$additionalData['exception'] = '#' . $exception->getCode() . ': ' . $exception->getMessage();
}
$this->systemLogger->log('Mail delivery failed.', LOG_ERR, $additionalData);
}
}
<?php
namespace Vendor\MyPackage\Mail;
use TYPO3\Flow\Annotations as Flow;
/**
* @Flow\Scope("prototype")
*/
class Recipient {
/**
* @var string
*/
protected $emailAddress = '';
/**
* @var string
*/
protected $name = '';
/**
* @param string $emailAddress
* @param string $name
*/
public function __construct($emailAddress, $name = '') {
$this->emailAddress = $emailAddress;
$this->name = $name;
}
/**
* @return string
*/
public function getEmailAddress() {
return $this->emailAddress;
}
/**
* @return bool
*/
public function hasName() {
return $this->getName() !== '';
}
/**
* @return string
*/
public function getName() {
return $this->name;
}
/**
* @return array
*/
public function toArray() {
if ($this->hasName()) {
return [
$this->getEmailAddress() => $this->getName()
];
}
return [
$this->getEmailAddress()
];
}
}
Vendor:
MyPackage:
mail:
sender:
emailAddress: '[email protected]'
name: 'Example'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment