Return to Snippet

Revision: 57102
at May 16, 2012 12:40 by squadsupply


Initial Code
// include class
	include("Net/POP3.php");
	 
	// initialize object
	$pop3 = new Net_POP3();

	// attempt connection to server
	if (!$pop3->connect("mail.yourserver.com", 110)) {
		die("Error in connection");
	}
	 
	// attempt login
	$ret = $pop3->login($email_login, $email_password);
	if (is_a($ret, 'PEAR_Error')) {
		die("Error in authentication: " . $ret->getMessage());
	}

	// print number of messages found
	echo $pop3->numMsg() . " message(s) in mailbox\n";

		
	// print message headers
	if ($pop3->numMsg() > 0) {
	

		for ($x=1; $x<=$pop3->numMsg(); $x++) {
		
		// for ($x=1; $x<=10; $x++) {
			$hdrs = $pop3->getParsedHeaders($x);

			
			if
			( 
				preg_match( '/MAILER-DAEMON/i', $hdrs['From'] ) || preg_match( '/Mail Administrator/i', $hdrs['From'] ) 
					|| 	
				preg_match( '/Returned mail/i', $hdrs['Subject'] ) || preg_match( '/User Unknown/i', $hdrs['Subject'] ) 
			) 
			{
	
				
				// extract the email address from the body
				$mail_body = $pop3->getBody($x);
				$pattern = '/[A-Za-z0-9_-]+@[A-Za-z0-9_-]+\.([A-Za-z0-9_-][A-Za-z0-9_]+)/'; //regex for pattern of e-mail address
				preg_match($pattern, $mail_body, $matches); //find matching pattern
   
				$undeliverable_email = $matches[0];
				
				echo "<b>Remove " . $undeliverable_email . "</b><br/><br/>";
				
// add to database table 'bad_emails' to prevent future mailings to this address
				if( mysql_query("INSERT INTO `bad_emails` (`email`) VALUES ('$undeliverable_email');") ) {
					
				}
				
				// delete the message
				$pop3->deleteMsg($x);
   
			}
			
		}
	}
	
	// disconnect from server
	$pop3->disconnect();

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

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

Initial Title
PHP Pear Remove Undeliverable Emails from POP3 Account

Initial Tags
php, mail

Initial Language
PHP