Download GMail emails with PHP

A practical application for download emails with IMAP and PHP is to download emails from GMail.

The first thing we have to do is confirm that we have activated IMAP access in our GMail. To do this we have to go to:

Mail Settings » Forwarding and POP/IMAP » IMAP Access

We select the Enable IMAP option and save the changes.

The second thing we have to know is that the IMAP server of GMail is accessed through the following settings:

$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = '[email protected]';
$password = 'password';

You have to be careful since port 993 is used to access via IMAP.

The following steps are the same as those explained in how to download emails with IMAP and PHP or how download emails with POP3 and PHP. But let’s leave the code printed:

$emails = imap_search($inbox,'ALL');
if($emails) {
  $output = '';
  foreach($emails as $email_number) {    
    $overview = imap_fetch_overview($inbox,$email_number,0);
    $output.= 'Subject: '.$overview[0]->subject;
    $output.= 'From: '.$overview[0]->from;    
  }  
  echo $output;
} 
imap_close($inbox);

Leave a Comment