首页 > 解决方案 > Messenger __invoke 方法中的 Swiftmailer 不发送邮件

问题描述

我目前在将 \Swift_Mailer 用于 Symfony MessageHandlerInterface 时遇到问题。在此类的 __invoke 方法中,我想使用 Swift_Mailer 发送电子邮件。

/**
 * @param MailMessage $mailMessage
 */
public function __invoke(MailMessage $mailMessage)
{
    try {
        $message = (new \Swift_Message('You Got Mail!'))
            ->setFrom('no-reply@example.be' , 'No reply')
            ->setTo('development@example.be')
            ->setBody(
                'hello world',
                'text/plain'
            )
        ;

        $successfulRecipientsCount = $this->mailer->send($message, $failedRecipients);
        if ($successfulRecipientsCount < 1 || count($failedRecipients) > 0) {
            throw new \Exception('error sending mail');
        }
    }  catch (\Exception $e) {
        $this->logger->error( $e->getMessage());
    }
}

但是当我想使用这些消息时,邮件程序永远不会将邮件发送到目的地。当我将此片段用于控制器时,它就可以工作。所以我的配置中的邮件参数没有问题。

我知道 Symfony 的控制器调度 kernel.terminate 事件,Swift_Mailer 利用这个事件发送电子邮件。

如何在 Symfony 的 MessengerHandlerInterface 的魔术方法 __invoke 中调度 kernel.terminate 事件?

标签: phpsymfony4swiftmailer

解决方案


推荐阅读