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 = '[email protected]';
$password = 'website@123';
$mailbox = '{imap.website.com:143}INBOX';
$mbx = imap_open($mailbox , $user , $password);
Next We search 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.
$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);
Now we are going to retrive the email’s body
$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);
To get subject of email
$subject =$overview[0]->subject;
And lastly we will set email flag as seen
imap_setflag_full($mbx, $overview[0]->uid, '\Seen');