Symfony:测试模式下的电子邮件:在电子邮件中指明邮件真正发送到的位置

时间:2018-04-22 20:25:09

标签: symfony swiftmailer symfony-3.4

当我使用symfony 3.4和swiftmailer发送电子邮件时,我可以设置一个参数来将所有电子邮件发送到定义的电子邮件(在开发环境中有意义):

swiftmailer:
    delivery_address: "development.email@myProjectDomain.com"

现在在电子邮件本身中,如果不设置此参数,我无法看到它会去哪里。我可以查看X-Swift-To变量的标题,但这非常麻烦......

我想要的是一个简单的信息作为邮件正文的第一行,如

This email would be sent to customer@yahoo.com in production

我怎样才能实现这一目标?是否有一些swiftmailer的配置才能做到这一点?因为当我设置swiftmailer并发送电子邮件时,我无法知道电子邮件实际发送到哪里...

1 个答案:

答案 0 :(得分:0)

我为我创建了一个处理这种东西的服务:

<?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);(我的邮件使用twig模板)

重定向除prod以外的环境中的邮件,并更改其主题行以包含原始收件人和当前环境。

请注意,我添加了一些额外的检查,以允许$recipient成为User实体或邮件/实体数组。