Sunday, June 9, 2013

SwiftMailer/Symfony2: Expected response code 250 but got code "421", with message "421 Timeout waiting for data from client.

I assume you are using Symfony2 and SwiftMailer to send emails via crontab and symfony2 command. I was using For-Loop in Symfony2 command line to send over hundreds of emails with AWS SES, but the error below was popping up randomly:

Expected response code 250 but got code "421", with message "421 Timeout waiting for data from client

After some search and knocking my head against the wall, I found the answer:

$this->getContainer()->get('mailer')->getTransport()->start();
$this->getContainer()->get('mailer')->send($message);
$this->getContainer()->get('mailer')->getTransport()->stop();

Yes, that's it. You need to start and stop the connection each time. I know it sucks, but this fixed my random error.

My entire command class would like something like below:

class TestEmailCommand extends ContainerAwareCommand
{

    protected function configure()
    {
        $this
                ->setName('test:email')
                ->setDescription('Test Email System')
        ;
    }

    protected function execute(InputInterface $input , OutputInterface $output)
    {

        $em = $this->getContainer()->get("doctrine")->getManager();

        $users = $em->getRepository('UserBundle:User')->findAllforEmails();

        foreach($users as $user)
        {

            $message = \Swift_Message::newInstance()
                    ->setSubject('Dummy Subject')
                    ->setFrom('dummy@example.com')
                    ->setTo($user->getEmail())
                    ->setBody('Dummy Body of the Email' , 'text/html');

            try
            {

                $this->getContainer()->get('mailer')->getTransport()->start();
                $this->getContainer()->get('mailer')->send($message);
                $this->getContainer()->get('mailer')->getTransport()->stop();
            }
            catch(\Exception $exc)
            {
                $output->writeln($exc->getTraceAsString());
            }
        }
    }
}