如何在 SwiftMailer 中关闭 SMTP 连接

2022-01-17 00:00:00 email smtp worker php swiftmailer

我使用 SwiftMailer 从 gearman 工作进程发送电子邮件.我正在使用 Swift_SmtpTransport 类发送电子邮件.

I use SwiftMailer to send emails from a gearman worker process. I'm using the Swift_SmtpTransport class to send emails.

问题是,如果这个工作进程保持空闲一段时间,SwiftMailer smtp 连接就会超时.现在,当下一个作业到达时,SwiftMailer 无法发送电子邮件,因为连接已超时.

The problem is that if this worker process stays idle for sometime, the SwiftMailer smtp connection times out. Now when the next job arrives, SwiftMailer fails to send emails as the connection has been timed out.

理想情况下,我希望在每次作业后关闭 smtp 连接.我无法在专门执行此操作的类中找到 api.unset() 对象也不起作用,因为这是一个静态类.

Ideally, I would want to close the smtp connection after every job. I'm unable to locate a api in the class which does this specifically. Neither does unset() object works since this is a static class.

推荐答案

有一个粗鲁的选择:明确停止传输.在随后调用 sendMail 方法时,SwiftMailer 将检查传输是否已启动(现在未启动)并再次启动它.IMNSHO,SwiftMailer 应该拦截 SMTP 超时并自动重新连接.但是,目前,这是解决方法:

There is a rude option: stop the transport explicitly. On subsequent calls of the method sendMail, SwiftMailer will check whether the transport is up (it is not, now) and start it again. IMNSHO, SwiftMailer should intercept the SMTP timeout and reconnect automatically.But, for now, this is the workaround:

function sendMail($your_args) {
    try{ 
      $mailer = Swift_Mailer::newInstance($transport);
      $message = Swift_Message::newInstance('Wonderful Subject')
        ->setFrom(array('john@doe.com' => 'John Doe'))
        ->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name'))
        ->setBody('Here is the message itself');

      $result = $mailer->send($message);
      $mailer->getTransport()->stop();

    } catch (Swift_TransportException $e) {
      //this should be caught to understand if the issue is on transport
    } catch (Exception $e) {
      //something else happened  
    }

}

相关文章