PHP Pear Remove Undeliverable Emails from POP3 Account


/ Published in: PHP
Save to your folder(s)

You can set this as a cron to automatically clean up unsubscribes after sending out a mass email.


Copy this code and paste it in your HTML
  1. // include class
  2. include("Net/POP3.php");
  3.  
  4. // initialize object
  5. $pop3 = new Net_POP3();
  6.  
  7. // attempt connection to server
  8. if (!$pop3->connect("mail.yourserver.com", 110)) {
  9. die("Error in connection");
  10. }
  11.  
  12. // attempt login
  13. $ret = $pop3->login($email_login, $email_password);
  14. if (is_a($ret, 'PEAR_Error')) {
  15. die("Error in authentication: " . $ret->getMessage());
  16. }
  17.  
  18. // print number of messages found
  19. echo $pop3->numMsg() . " message(s) in mailbox\n";
  20.  
  21.  
  22. // print message headers
  23. if ($pop3->numMsg() > 0) {
  24.  
  25.  
  26. for ($x=1; $x<=$pop3->numMsg(); $x++) {
  27.  
  28. // for ($x=1; $x<=10; $x++) {
  29. $hdrs = $pop3->getParsedHeaders($x);
  30.  
  31.  
  32. if
  33. (
  34. preg_match( '/MAILER-DAEMON/i', $hdrs['From'] ) || preg_match( '/Mail Administrator/i', $hdrs['From'] )
  35. ||
  36. preg_match( '/Returned mail/i', $hdrs['Subject'] ) || preg_match( '/User Unknown/i', $hdrs['Subject'] )
  37. )
  38. {
  39.  
  40.  
  41. // extract the email address from the body
  42. $mail_body = $pop3->getBody($x);
  43. $pattern = '/[A-Za-z0-9_-]+@[A-Za-z0-9_-]+\.([A-Za-z0-9_-][A-Za-z0-9_]+)/'; //regex for pattern of e-mail address
  44. preg_match($pattern, $mail_body, $matches); //find matching pattern
  45.  
  46. $undeliverable_email = $matches[0];
  47.  
  48. echo "<b>Remove " . $undeliverable_email . "</b><br/><br/>";
  49.  
  50. // add to database table 'bad_emails' to prevent future mailings to this address
  51. if( mysql_query("INSERT INTO `bad_emails` (`email`) VALUES ('$undeliverable_email');") ) {
  52.  
  53. }
  54.  
  55. // delete the message
  56. $pop3->deleteMsg($x);
  57.  
  58. }
  59.  
  60. }
  61. }
  62.  
  63. // disconnect from server
  64. $pop3->disconnect();

URL: http://www.squadsupply.com/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.