我创建了一个为我处理这类事情的服务:
<?php
namespace AppBundle\Util;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Templating\EngineInterface;
use Swift_Mailer;
use AppBundle\Entity\User;
class MailService
{
private $em;
private $templating;
private $mailer;
private $env;
public function __construct(EntityManager $entityManager, EngineInterface $templating, Swift_Mailer $mailer,$env)
{
$this->em = $entityManager;
$this->templating = $templating;
$this->mailer = $mailer;
$this->env = $env;
}
private function doSend($subject, $to, $template, $vars = array())
{
$message = \Swift_Message::newInstance();
$body = $this->templating->render($template, $vars);
$message->setSubject($subject)
->setFrom("foo@bar.com")
->setTo($to)
->setBody(
$body,
"text/html"
);
if ($this->env != "prod") // Redirect mails in dev/staging environments
{
$message->setSubject("[".$this->env." ".$to."] ".$subject);
$message->setTo("my_dev_mail@foo.com"); // hardcoded for my case, could be changed to config parameter though...
}
$this->mailer->send($message);
}
public function Send($subject, $to, $template, $vars = array())
{
$type = gettype($to);
switch($type)
{
case "string":
$this->doSend($subject, $to, $template, $vars);
break;
case "array":
foreach($to as $t)
{
$this->Send($subject, $to, $template, $vars);
}
break;
case "object":
if ($to instanceof User)
{
$this->Send($subject, $to->getEmail(), $template, $vars);
} elseif (is_iterable($to))
{
foreach($to as $t)
{
$this->Send($subject, $t, $template, $vars);
}
}
break;
default:
throw \Exception("Unknown Recipient Type.");
}
}
}
然后我可以使用$this->get("my.mailer")->Send($subject, $recipient, $template, $templateVars);(我的邮件使用树枝模板)
prod 以外的环境中的邮件会被重定向,并且其主题行会更改为包含原始收件人和当前环境。
请注意,我添加了一些额外的检查以允许 $recipient 成为 User 实体或邮件/实体数组。