【问题标题】:Symfony Swiftmailer: Conditionally spool emails or send immediatelySymfony Swiftmailer:有条件地假脱机电子邮件或立即发送
【发布时间】:2018-04-13 19:04:40
【问题描述】:

有没有人设置过在 Symfony 中使用 Swiftmailer 假脱机电子邮件的条件? 我希望可以选择是立即发送我的电子邮件,还是将它们存储在一个文件中,具体取决于我正在运行的功能。

我将电子邮件服务抽象在一个自己的 Bundle 中,并在需要时调用其他 Bundle 中的 sendEmail() 函数。但是对于某些捆绑包/功能,我希望立即发送电子邮件,而对于其他捆绑包/功能,假脱机很好。我曾考虑在我的 sendEmail() 函数中使用 spool 参数,因此如果在调用该函数时将参数设置为 true,则电子邮件会被假脱机,如果设置为 false,则会立即发送。

或者一个简单的 if 条件就足够了?]

任何想法、提示、经验等都会很棒!

更新

在我的 config.yml 中:

# Swiftmailer Configuration
swiftmailer:
    transport: "%mailer_transport%"
    host:      "%mailer_host%"
    username:  "%mailer_user%"
    password:  "%mailer_password%"
    spool:
          type: file
          path: /srv/http/test/spool

【问题讨论】:

  • Swiftmailer 支持spooling by default,你只需要设置一个 cron 作业定期运行以清除假脱机
  • 但是如果我不希望我的电子邮件被假脱机怎么办?我只希望他们在某些情况下被假脱机。这就是我打算用我的问题说的
  • 这是可能的,你能说明Swift_Mailer 实例是如何被加载/配置的​​吗?
  • 是的,我把它添加到我的问题@WilliamPerron :)

标签: symfony email conditional-statements swiftmailer spool


【解决方案1】:

通过在参数中指定spool 选项,Swiftmailers 将使用Swift_Transport_SpoolTransport 的实例,它将通过将消息发送到队列而不是直接将它们发送到世界来管理假脱机。通过Transport 对象,您可以访问Spool 实例(Swift_MemorySpoolSwift_FileSpool)并强制 Swiftmailer 刷新队列。

// custom function to send an email
// inject \Swift_Mailer like you normally would
public function sendMessage($name, \Swift_Mailer $mailer, $bypassSpool = false)
{
    $message = new \Swift_Message('Hello Email')
        ->setFrom(/* from */)
        ->setTo(/* to */)
        ->setBody(/* render view */);

    $mailer->send($message); // pushes the message to the spool queue

    if($bypassSpool) {
        $spool = $mailer->getTransport->getSpool()
        $spool->flushQueue(new Swift_SmtpTransport(
            /* Get host, username and password from config */
        ));
    }
}

【讨论】:

  • 在我将您的答案标记为一个快速问题之前:是否真的有必要将参数添加到新的 Transport 实例?我在没有参数的情况下尝试了它,它成功了,但我想知道添加参数会有什么区别?
  • 哦,还有一个问题:有没有办法只刷新当时创建的消息?因为当我现在刷新队列时,很明显,我的假脱机文件中的所有消息都会被发送出去。
  • @sonja 回答您的第一个问题:也许吧。我还没有尝试过并坚持使用官方文档的答案,但如果它默认为配置参数,我不会感到惊讶。对于你的第二个问题,当然,但你需要每次都创建一个 Swift_FileSpool 的新实例,因为更改保存路径的唯一方法是通过构造函数,然后创建一个 Swift_Mailer 的新实例,因为你可以Transport 初始化后就不要改了
  • @sonja,我认为由此产生的复杂性是不值得的。我会简单地使用MemorySpool,它会在内核终止时(即请求结束时)刷新其队列,因此它不会成为请求的瓶颈
  • 非常感谢!我考虑为那个场合添加第二个假脱机文件,但找不到其他人已经这样做了。您知道这是否会起作用或如何起作用吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-16
  • 1970-01-01
  • 2019-10-05
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
相关资源
最近更新 更多