Skip to content

Instantly share code, notes, and snippets.

@wonzbak
Last active January 4, 2017 11:01
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 wonzbak/852f6fba54bbc35b877f252ae00dca37 to your computer and use it in GitHub Desktop.
Save wonzbak/852f6fba54bbc35b877f252ae00dca37 to your computer and use it in GitHub Desktop.
Mailer Symfony 2/3
<?php
class Mailer
{
/** @var \Swift_Mailer */
private $mailer;
/** @var \Swift_Transport_AbstractSmtpTransport */
private $transport;
/**
* Mailer constructor.
*
* @param \Swift_Mailer $mailer
* @param \Swift_Transport_AbstractSmtpTransport $transport
*/
public function __construct(
\Swift_Mailer $mailer,
\Swift_Transport_AbstractSmtpTransport $transport
) {
$this->mailer = $mailer;
$this->transport = $transport;
}
/**
* Create a email message.
*
* @param array $recipients List of recipient with: to, cc, bcc key.
* @param string $subject Subject of the email.
* @param string $htmlBody Html content of the email.
*
* @return \Swift_Mime_SimpleMimeEntity
*/
final public function createMessage(array $recipients, $subject, $htmlBody)
{
$message = \Swift_Message::newInstance()
->setSubject($subject)
->setFrom("noreply@edd.fr")
->setTo($recipients['to'])
->setCc($recipients['cc'])
->setBcc($recipients['bcc'])
->setContentType('text/html')
->setBody($htmlBody, 'text/html');
return $message;
}
/**
* Send an email message or a list of messages.
*
* @param mixed $messages A \Swift_Message or a list of \Swift_Message.
*/
final public function sendAndFlush($messages)
{
if (is_array($messages) || $messages instanceof \Traversable) {
foreach ($messages as $message) {
$this->mailer->send($message);
}
} else {
$this->mailer->send($messages);
}
$this->flush();
}
final public function flush()
{
// below to ensure mail is actualy sending
$spool = $this->mailer->getTransport()->getSpool();
$spool->flushQueue($this->transport);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment