Reading emails from gmail.com via IMAP in PHP

Since I'm a freelancer (unemployed) I work with a friend of mine on a few smaller websites.

Recently I was trying to make some automatic payment processing. Basically, e-banking sends you an email for each incoming payment and I have a cron job that checks for new emails via IMAP and somehow processes its content.

I think this should work on every email service with IMAP protocol but I was really surprised how is to use it. Although, I'm connecting to gmail.com, the basic principle should be the same for other email services as well.

Ok, before you start make sure you have imap extension for php. If not, install it with sudo apt-get install php-imap, sudo port install php-imap or whatever.

Let's first connect to gmail's IMAP and handle errors:

 1 
 2 
 3 
 4 
 5 
 6 
$imap_client = imap_open('{imap.gmail.com:993/imap/ssl}INBOX', 'hello@gmail.com', 'password');

if (!$imap_client) {
    echo imap_last_error();
    exit;
}

Now you can check some basic information about your mailbox like number of unread messages, etc...

 1 
 2 
 3 
 4 
 5 
 6 
 7 
 8 
 9 
 10 
 11 
 12 
 13 
 14 
 15 
$info = imap_mailboxmsginfo($imap_client);

/*
this returns stdObject with some basic info:
object(stdClass)#39 (8) {
  ["Unread"]=> int(308)
  ["Deleted"]=> int(0)
  ["Nmsgs"]=> int(1200)
  ["Size"]=> int(133048013)
  ["Date"]=> string(36) "Wed, 5 Dec 2012 00:19:15 +0100 (CET)"
  ["Driver"]=> string(4) "imap"
  ["Mailbox"]=> string(79) "{gmail-imap.l.google.com:993/imap/notls/ssl/user="hello@gmail.com"}INBOX"
  ["Recent"]=>int(0)
}
*/

Also, you can directly search emails for some criteria and get their bodies:

 1 
 2 
 3 
 4 
 5 
 6 
 7 
 8 
// this returns just email ids
$emails = imap_search($imap_client, 'UNSEEN');

// in order yo get their content we have to call imap_body on each of them
foreach ($emails as $email_id) {
    $body = imap_body($imap_client, $email_id);
    // analyze $body
}

Just one important note here. Calling imap_body automatically sets \Seen flag. If you want to keep your emails marked as unseen set third parameter of imap_body to FT_PEEK (for more info see manual).

Very useful functionality is that you can combine multiple search criteria in imap_search and for example search only for unread email from one particular sender:

imap_search($imap_client, 'UNSEEN FROM "friend@gmail.com"')

I know this is very short tutorial, but I believe it's enough to start using IMAP in PHP because it's very simple yet powerful.

blog comments powered by Disqus