Skip to content

Instantly share code, notes, and snippets.

@boekkooi
Last active November 18, 2015 13:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boekkooi/044f1d4a1c87cd60407f to your computer and use it in GitHub Desktop.
Save boekkooi/044f1d4a1c87cd60407f to your computer and use it in GitHub Desktop.
PHP Twig Mailer
<?php
final class ExampleMailer extends Mailer
{
protected $parameters;
public function __construct(\Swift_Mailer $mailer, UrlGeneratorInterface $router, \Twig_Environment $twig, array $parameters)
{
parent::__construct($mailer, $router, $twig);
$this->parameters = $parameters;
}
/**
* {@inheritdoc}
*/
public function sendMemberInviteMessage(MemberInvite $invite)
{
$template = $this->parameters['template']['member_invite_verification'];
$url = $this->getUrlGenerator()->generate(
'xoip_profile_company_member_invite_verification',
[
'company' => $invite->getCompany(),
'memberInvite' => $invite->getConfirmationToken()
],
true
);
$context = [
'email' => $invite->getEmail(),
'name' => $invite->getEmail(),
'company' => $invite->getCompany(),
'confirmationUrl' => $url,
];
$this->sendMessage($template, $context, $this->parameters['from_email']['member_invite_verification'], $invite->getEmail());
}
}
<?php
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
abstract class Mailer
{
/**
* @var \Swift_Mailer
*/
private $mailer;
/**
* @var UrlGeneratorInterface
*/
private $router;
/**
* @var \Twig_Environment
*/
private $twig;
public function __construct(\Swift_Mailer $mailer, UrlGeneratorInterface $router, \Twig_Environment $twig)
{
$this->mailer = $mailer;
$this->router = $router;
$this->twig = $twig;
}
protected function getUrlGenerator()
{
return $this->router;
}
/**
* @param string $templateName
* @param array $context
* @param string $fromEmail
* @param string $toEmail
* @param array $attachments
*/
protected function sendMessage($templateName, array $context, $fromEmail, $toEmail, array $attachments = [])
{
$context = $this->twig->mergeGlobals($context);
/** @var \Twig_Template $template */
$template = $this->twig->loadTemplate($templateName);
$subject = $template->renderBlock('subject', $context);
$textBody = $template->renderBlock('body_text', $context);
$htmlBody = $template->renderBlock('body_html', $context);
$message = \Swift_Message::newInstance();
$message->setSubject($subject)
->setFrom($fromEmail)
->setTo($toEmail);
if (!empty($htmlBody)) {
$message->setBody($htmlBody, 'text/html');
$message->addPart($textBody, 'text/plain');
} else {
$message->setBody($textBody);
}
foreach ($attachments as $name => $filePath) {
$fileName = $name.'.'.pathinfo($filePath, PATHINFO_EXTENSION);
$message->attach(
\Swift_Attachment::fromPath($filePath)
->setFilename($fileName)
);
}
$this->mailer->send($message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment