Chris & Computers

Tips, tricks, muses and other computer related scibblings. Mostly for myself, maybe useful to others.

Jun 22

php + imap + gmail Step 1 of 3

Using php to check new emails in gmail.

Proof of concept put togther after listening to Techzing 48 – The Depressed Designer, in regards to using a server to interact with mail.

Having recently been interacting with a server and gmail, listening to Justin and Jason, in this case Jason talking about a back and forth interaction via email with his clients in a semi automated way. I finally got the urge to reply to them in more than just a comment.

Why use gmail, instead of running your own. ( off the cuff reasons )

  • You don’t need to run extra proccesses on your server allowing you to use more ram for more important tasks.
  • Using gmail as your mail server frees you up to focus on your core web application.
  • Google and there engineers can deal with mail spam and attacks.

3 scripts.

  1. Check for unread emails.
  2. Check for unread emails with “techzinglive” in the subject.
  3. Check for unread emails in a “lablel”. ( A label in google is a folder to imap )
$hostname = '{}';

$username = 'Email address here';
$password = 'Password Here';

if( empty( $password ) )
die('Write password in');

/* try to connect */
$inbox = imap_open ( $hostname, $username, $password ) or die('Cannot connect to Gmail: ' . imap_last_error() );

$emails = imap_search($inbox,'UNSEEN');

if( !$emails )
echo 'Nothing to read' . "\n";

foreach( $emails as $msg_id )
$header = imap_headerinfo($inbox,$msg_id );
echo "$header->subject". "\n";

/* close the connection */