Skip to content

Instantly share code, notes, and snippets.

@bwaidelich
Last active May 23, 2016 13:35
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save bwaidelich/5967024 to your computer and use it in GitHub Desktop.
Save bwaidelich/5967024 to your computer and use it in GitHub Desktop.
Simple Email Service for TYPO3 Flow
<?php
namespace My\Package\Service;
use TYPO3\Flow\Annotations as Flow;
/**
* @Flow\Scope("singleton")
*/
class EmailService {
/**
* @Flow\Inject
* @var \TYPO3\Flow\Log\SystemLoggerInterface
*/
protected $systemLogger;
/**
* @Flow\Inject
* @var \TYPO3\Flow\Configuration\ConfigurationManager
*/
protected $configurationManager;
/**
* @Flow\Inject
* @var \TYPO3\Flow\Mvc\Routing\RouterInterface
*/
protected $router;
/**
* @param string $templateIdentifier name of the email template to use @see renderEmailBody()
* @param string $subject subject of the email
* @param array $sender sender of the email in the format array('<emailAddress>' => '<name>')
* @param array $recipient recipient of the email in the format array('<emailAddress>' => '<name>')
* @param array $variables variables that will be available in the email template. in the format array('<key>' => '<value>', ....)
* @return boolean TRUE on success, otherwise FALSE
*/
public function sendTemplateBasedEmail($templateIdentifier, $subject, array $sender, array $recipient, array $variables = array()) {
$this->initializeRouter();
$plaintextBody = $this->renderEmailBody($templateIdentifier, 'txt', $variables);
$htmlBody = $this->renderEmailBody($templateIdentifier, 'html', $variables);
$mail = new \TYPO3\SwiftMailer\Message();
$mail
->setFrom(array($sender['email'] => $sender['name']))
->setTo(array($recipient['email'] => $recipient['name']))
->setSubject($subject)
->setBody($plaintextBody)
->addPart($htmlBody, 'text/html');
return $this->sendMail($mail);
}
/**
* @param string $templateIdentifier
* @param string $format
* @param array $variables
* @return string
*/
protected function renderEmailBody($templateIdentifier, $format, array $variables) {
$standaloneView = new \TYPO3\Fluid\View\StandaloneView();
$request = $standaloneView->getRequest();
$request->setControllerPackageKey('My.Package');
$templatePathAndFilename = sprintf('resource://My.Package/Private/EmailTemplates/%s.%s', $templateIdentifier, $format);
$standaloneView->setTemplatePathAndFilename($templatePathAndFilename);
$standaloneView->assignMultiple($variables);
return $standaloneView->render();
}
/**
* Sends a mail and creates a system logger entry if sending failed
*
* @param \TYPO3\SwiftMailer\Message $mail
* @return boolean TRUE on success, otherwise FALSE
*/
protected function sendMail(\TYPO3\SwiftMailer\Message $mail) {
$numberOfRecipients = 0;
// ignore exceptions but log them
$exceptionMessage = '';
try {
$numberOfRecipients = $mail->send();
} catch (\Exception $e) {
$exceptionMessage = $e->getMessage();
}
if ($numberOfRecipients < 1) {
$this->systemLogger->log('Could not sent notification email "' . $mail->getSubject() . '"', LOG_ERR, array(
'exception' => $exceptionMessage,
'message' => $mail->getSubject(),
'id' => (string)$mail->getHeaders()->get('Message-ID')
));
return FALSE;
}
return TRUE;
}
/**
* Initialize the injected router-object
*
* @return void
*/
protected function initializeRouter() {
$routesConfiguration = $this->configurationManager->getConfiguration(\TYPO3\Flow\Configuration\ConfigurationManager::CONFIGURATION_TYPE_ROUTES);
$this->router->setRoutesConfiguration($routesConfiguration);
}
}
?>
@bwaidelich
Copy link
Author

bwaidelich commented Jul 18, 2013

Usage:

/**
 * @Flow\Inject
 * @var \My\Package\Service\EmailService
 */
protected $emailService;

// ...

$this->emailService->sendTemplateBasedEmail(
    'RegistrationConfirmationOutgoing',
    'Please confirm registration',
    array('admin@example.com' => 'sender'),
    array('recipient@example.com' => 'recipient'),
    array('variables' => 'available', 'in' => 'template')
);

@bwaidelich
Copy link
Author

Note: Initialization of the router (line 101ff) and definition of package key (line 61) is done so that links work in the templates even when invoked from the CLI

@bwaidelich
Copy link
Author

FYI: With Flow 3.0+ you won't need to initialize the router explicitly, so you can omit the initializeRouter() and you won't have to inject the router

@putheakhem
Copy link

@bwidelich . where i can create the class EmailService and how to test it. Because i'm a beginner with flow

@bwaidelich
Copy link
Author

@putheakhem I missed your comment (you misspelled my handle so I wasn't notified). The PHP namespace reflects the location of a class, in this case I've just put it in a subfolder Service

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment