gpt4 book ai didi

symfony - Swiftmailer 不立即发送

转载 作者:行者123 更新时间:2023-12-02 17:29:14 26 4
gpt4 key购买 nike

我已成功配置我的 symfony web 应用程序以使用 SMTP 发送电子邮件。但我所有发送的电子邮件都被放入 spool 目录中。

只有在发送错误时才会发生这种情况。这是正确的吗?

但是如果我执行命令 swiftmailer:spool:send --env=prod,我的所有电子邮件都会正确发送。

为什么我的服务器没有立即发送电子邮件?是因为我修正了一个错误吗?有什么办法可以解决这个问题吗?

swiftmailer:

spool:
type: file
path: %kernel.root_dir%/spool

最佳答案

如果有人通过消息队列(symfony/messenger)处理电子邮件,则使用内存假脱机是首选。但是,内存假脱机仅在 Kernel::terminate 事件上进行处理。长时间运行的控制台工作线程永远不会发生此事件。

此内核事件正在调用 Symfony\Bundle\SwiftmailerBundle\EventListener\EmailSenderListener::onTerminate() 方法。您可以通过分派(dispatch)您自己的事件并订阅上述方法来手动调用此方法。

src/App/Email/Events.php

<?php

namespace App\Email;

class Events
{
public const UNSPOOL = 'unspool';
}

config/services.yml

services:    
App\Email\AmqpHandler:
tags: [messenger.message_handler]

Symfony\Bundle\SwiftmailerBundle\EventListener\EmailSenderListener:
tags:
- name: kernel.event_listener
event: !php/const App\Email\Events::UNSPOOL
method: onTerminate

你的消息队列 worker src/App/Email/AmqpHandler.php

<?php

namespace App\Email;

use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class AmqpHandler
{
/** @var EventDispatcherInterface */
private $eventDispatcher;

/** @var Swift_Mailer */
private $mailer;

public function __construct(EventDispatcherInterface $eventDispatcher, Swift_Mailer $mailer)
{
$this->eventDispatcher = $eventDispatcher;
$this->mailer = $mailer;
}

public function __invoke($emailMessage): void
{
//...
$message = (new Swift_Message($subject))
->setFrom($emailMessage->from)
->setTo($emailMessage->to)
->setBody($emailMessage->body, 'text/html');

$successfulRecipientsCount = $this->mailer->send($message, $failedRecipients);
if ($successfulRecipientsCount < 1 || count($failedRecipients) > 0) {
throw new DeliveryFailureException($message);
}

$this->eventDispatcher->dispatch(Events::UNSPOOL);
}
}

您可以阅读有关 symfony/messenger here 的信息.

关于symfony - Swiftmailer 不立即发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29802225/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com