Parse Emails Using IMAP

Recently I have worked on project where I had to parse incoming emails and find out who send it and depending on the message run certain DBMS tasks. PHP’s IMAP Functions are quite efficient. You can can retrive emails using these functions in no time.

To Get emails we first need to make a connection with the host.

$host = 'imap.website.com:143';
$user = 'me@website.com';
$password = 'website@123';
$mailbox = '{imap.website.com:143}INBOX';

$mbx = imap_open($mailbox , $user , $password);
try
{
	$check = imap_check($mbx);
}catch(Exception $e)
{
	echo $e->getMessage();
	exit;
}

Next We are searching for all new emails.

try
{
	$email_numbers = imap_search($mbx, 'UNSEEN');
}catch(Exception $e)
{
	echo $e->getMessage();
	exit;
}

The ‘UNSEEN’ is used because we want to retrive only the emails that are not read yet.

Now we going to get sender email address, mail body. After that we going to set the email as SEEN. If try catch block found any error, we will continue for next email and so on.

foreach($email_numbers as $email_uid)
{
	try
	{
		$overview = imap_fetch_overview($mbx,$email_uid);
	}catch(Exception $e)
	{
		echo $e->getMessage();
		continue;
	}
					
	$from_email='';	
	$header_details = imap_fetchheader($mbx,$email_uid); 
	$pattern = '/(envelope-from=)(.*)(;)/imxsU';
	preg_match($pattern, $header_details, $email_info);
	if(isset($email_info[2]) and $email_info[2] !='')
		$from_email = $email_info[2];

	if($from_email=='')
	{
		$pattern = '/(Return-Path:)(.*)(>)/imxsU';
		preg_match($pattern, $header_details, $email_info);	
		$from_email=str_replace(array('<', '>'), array('', ''), $email_info[2]);
	}

	if($from_email=='')
	{
		try
		{
			$header = imap_headerinfo($mbx, $overview[0]->uid);
		}catch(Exception $e)
		{
			echo $e->getMessage();
			continue;
		}
		
		if($header)
		{
			$from_email = $header->from[0]->mailbox . "@" . $header->from[0]->host;
		}
	}
	$from_email=trim($from_email);

	$mail_body = imap_fetchbody($mbx, $overview[0]->uid, "1.1", FT_UID );
	if ($mail_body == "") {
		$mail_body = imap_fetchbody($mbx, $overview[0]->uid, "1", FT_UID );
	}
	$text_mail_body = strip_tags($mail_body);

	$subject = strtoupper($overview[0]->subject);	
	imap_clearflag_full($mbx, $overview[0]->uid, '\\Seen');
}

About Zakir Hyder

This entry was written by .

23. November 2012 by Zakir Hyder
Categories: PHP | Tags: , , | Comments

Comments

  1. […] Parse Emails Using IMAP November 23, 2012 4:33 PM Recently I have worked on project where I had to parse incoming emails and find out who send it and depending on the message run certain DBMS tasks. PHP’s IMAP Functions are quite efficient. You can can retrive emails using these functions in no time. To Get emails we first need to make a connection […] […]