Wednesday, October 07, 2009

Gotcha Of The Day: Diagnosing PHP Mail_Queue Errors

I find the PEAR Mail_Queue package to be an effective way to send out hundreds of messages from PHP. It works just like you'd want it to: your code just adds messages to the queue, and then a standard cron job like the code below runs and processes the queue:

 $queue = the_mail_queue(); // properly create the mail queue
 $queue->sendMailsInQueue(200);

This package is especially handy for testing out new code, as you can disable the cron job that empties the queue, run the new code, and then review the mail queue manually for errors and malformed messages.

I love that mail queue is so transparently stored in the database. It means that I can easily examine and tweak the mail queue without using any special tools. A few trivial SQL statements are all it takes.

My problem this morning was that the updated code I wrote added messages to the queue that looked perfect, yet the sending process was failing. The messages weren't leaving the queue, and the retry count was maxing out at 25.

I needed to find a way to diagnose the specific error that was causing these messages to fail. Turns out, this was easy to do - I just needed to use the >sendMailById function. This function does exactly the same thing as emptying the queue, but: (a) operates on a single message and (b) returns any errors it may have. I tweaked the above script to say:

$queue = the_mail_queue();
$xx = $queue->sendMailById(665248);
var_dump($xx);

And sure enough, I got a detailed message dumped to my screen.

The problem? I had chosen a From: address for these messages that didn't exist, and then message was failing as a result. I deleted the queue, and re-ran my code. Now when I attempted to send the messages they went through without a hitch.

No comments:

Post a Comment