Last active
January 4, 2017 11:01
-
-
Save wonzbak/852f6fba54bbc35b877f252ae00dca37 to your computer and use it in GitHub Desktop.
Mailer Symfony 2/3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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("[email protected]") | |
->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