Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close Smtp connection in SwiftMailer

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

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.

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.

like image 947
Nands Avatar asked Nov 06 '12 18:11

Nands


People also ask

How swiftmailer works?

Swift Mailer is a component-based mailing library, which is compatible with PHP web apps. It was created by SensioLabs, a French company famous for its open-source software community commitment and in particular, for the creation of the Symfony framework.

What is swiftmailer?

Swift Mailer is a component based library for sending e-mails from PHP applications.


1 Answers

I send mails in a loop and I was catching the Swift_TransportException and creating a new instance of Swift_Mailer but it wasn't the right fix: the problem is the transport, not the mailer. The solution is to issue an explicit call to Swift_SmtpTransport::stop():

foreach($recipients as $to => $body){
    try{
        $message->setTo($to);
        $message->setBody(body);
        $mailer->send($message);
    }catch(Swift_TransportException $e){
        $mailer->getTransport()->stop();
        sleep(10); // Just in case ;-)
    }
}

This way, Swift detects the mailer is stopped and starts it automatically, so it recovers correctly from communication errors.

like image 185
Álvaro González Avatar answered Sep 27 '22 18:09

Álvaro González