Handling Bouncing Email with VERP and PHP

If you’re planning to make your own mailing list software from scratch, bouncing messages will be one of the cases that you’ll have to handle. Fortunately, the magnificent D.J. Bernstein came up with VERP.

VERP stands for Variable Envelope Return Path. Bernstein, original author of qmail, djbdns and daemontools among others, has the technique published on his site.

In summary, this is what you need to do for VERP:

  • Create a catch-all or variable mailbox
  • Set the return path in a format that the recepient address is still readable
  • Fetch all email with formatted to your return path
  • Process your bounced message

The following is an example return path for a mailing list called foo:
foo-admin-john.smith=example.com@yourdomain.com

To set the return path with PHP’s mail function, pass the return path in the additional_parameters like the following:
mail('john.smith@example.com', 'Hello, world!', 'How are you doing today?', '', '-ffoo-admin-john.smith=example.com@yourdomain.com');

Below is an example for fetching bounced messages with VERP from a POP mailbox with PHP’s IMAP extension.


<?php
$mailbox = imap_open('{mail.yourdomain.com/pop3}', 'foo-admin', 'password');
$mailbox_info = imap_check($mailbox);
for($i = 1; $i <= $mailbox_info->Nmsgs; $i++)
{
  $msg_overview = imap_fetch_overview($mailbox, $i);
  $rcpt = $msg[0]->to;
  if(substr($rcpt, 0, 9) == 'foo-admin')
  {
    $target = substr($rcpt, 10); // exclude 'foo-admin='
    $target = substr($target, 0, -15); // exclude '@yourdomain.com'
    $target = str_replace('=', '@', $target); // revert '=' to '@'
    processBouncedEmail($target); // do whatever you want from here
    imap_delete($mailbox, $i); // you can delete the bounce message too
  }
}
imap_expunge($mailbox); // deletes messages marked with imap_delete()
imap_close($mailbox); // close the mailbox :)
?>

That’s how simple it is. I thought it was complicated too.

  • well, How does one route bounced email notifications to a php script that google apps would be getting?
  • Is there any email sending simulating software by which you can verify the good and bad emails in a mailing list?
blog comments powered by Disqus
Locations of visitors to this page
De La Salle Canlubang Top Sites top blogs Best blogs on the Web: all about WWW