Read Gmail Emails using PHP & IMAP

It is very easier to retrieve emails from Gmail account with the help of PHP and its IMAP extension.

Read Gmail is now very easier than we can think with the help of PHP and its IMAP extension that matches the given search criteria.
You need to meet the minimum requirements for this:

  • PHP version >= PHP5+
  • Enable IMAP Extension in your PHP installation
  • In you Gmail account settings, IMAP should be enabled

Enable IMAP in XAMPP:

  • Go to php.ini file
  • search for “;extension=php_imap.dll”
  • Remove the beginning semicolon i.e. “extension=php_imap.dll”

Enable IMAP in Linux:

  • Using command line “apt-get install php5-imap” install the PHP5 IMAP module
  • Enable it by “php5enmod imap”
  • Restart Apache using “service apache2 restart”

Using imap_search you can get an array of messages that matches the given search criteria.

Here is the list of criteria entries:

 ALL - return all messages matching the rest of the criteria
 ANSWERED - match messages with the \ANSWERED flag set
 BCC "string" - match messages with "string" in the Bcc: field
 BEFORE "date" - match messages with Date: before "date"
 BODY "string" - match messages with "string" in the body of the message
 CC "string" - match messages with "string" in the Cc: field
 DELETED - match deleted messages
 FLAGGED - match messages with the \FLAGGED (sometimes referred to as Important or Urgent) flag set
 FROM "string" - match messages with "string" in the From: field
 KEYWORD "string" - match messages with "string" as a keyword
 NEW - match new messages
 OLD - match old messages
 ON "date" - match messages with Date: matching "date"
 RECENT - match messages with the \RECENT flag set
 SEEN - match messages that have been read (the \SEEN flag is set)
 SINCE "date" - match messages with Date: after "date"
 SUBJECT "string" - match messages with "string" in the Subject:
 TEXT "string" - match messages with text "string"
 TO "string" - match messages with "string" in the To:
 UNANSWERED - match messages that have not been answered
 UNDELETED - match messages that are not deleted
 UNFLAGGED - match messages that are not flagged
 UNKEYWORD "string" - match messages that do not have the keyword "string"
 UNSEEN - match messages which have not been read yet

Step to do before running the code:

  • Login to your gmail account, enable imap.
  • Access this first: https://www.google.com/settings/security/lesssecureapps
  • Go to: https://accounts.google.com/b/0/DisplayUnlockCaptcha and enable access
You may like:  Word Cutter function in PHP

Read Also: Match a backslash with preg_match() in PHP

Here is the PHP script for getting your Gmail emails Using IMAP.

<?php
/* Create gmail connection */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'YOUR-EMAIL@GMAIL.COM';
$password = 'YOUR-PASSWORD';
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

/* Fetch emails */
$emails = imap_search($inbox,"ALL");

/* If emails are returned, cycle through each... */
if($emails) {
$output = '';

/* Make the newest emails on top */
rsort($emails);

/* For each email... */
foreach($emails as $email_number) {

$headerInfo = imap_headerinfo($inbox,$email_number);
$structure = imap_fetchstructure($inbox, $email_number);

/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);

/* get mesage body */
$message = imap_qprint(imap_fetchbody($inbox,$email_number,2));

/*
// If attachment found use this one
// $message = imap_qprint(imap_fetchbody($inbox,$email_number,"1.2"));
*/

$output .= 'Subject: '.$overview[0]->subject.'<br />';
$output .= 'Body: '.$message.'<br />';
$output .= 'From: '.$overview[0]->from.'<br />';
$output .= 'Date: '.$overview[0]->date.'<br />';
$output .= 'CC: '.$headerInfo->ccaddress.'<br />';

//  Attachments
$attachments = array();
if(isset($structure->parts) && count($structure->parts))
{
for($i = 0; $i < count($structure->parts); $i++)
{
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);

if($structure->parts[$i]->ifdparameters)
{
foreach($structure->parts[$i]->dparameters as $object)
{
if(strtolower($object->attribute) == 'filename')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}

if($structure->parts[$i]->ifparameters)
{
foreach($structure->parts[$i]->parameters as $object)
{
if(strtolower($object->attribute) == 'name')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}

if($attachments[$i]['is_attachment'])
{
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);

/* 3 = BASE64 encoding */
if($structure->parts[$i]->encoding == 3)
{
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
/* 4 = QUOTED-PRINTABLE encoding */
elseif($structure->parts[$i]->encoding == 4)
{
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}

foreach($attachments as $attachment)
{
if($attachment['is_attachment'] == 1)
{
$filename = $attachment['name'];
if(empty($filename)) $filename = $attachment['filename'];
$file_path = 'upload/'; //  Upload folder
$fp = fopen($file_path . $filename, "w+");
fwrite($fp, $attachment['attachment']);
fclose($fp);
}
}
//  Attachments

/* change the status */
$status = imap_setflag_full($inbox, $overview[0]->msgno, "\Seen \Flagged");
}

echo $output;
}

/* close the connection */
imap_close($inbox);
?>

So, with our individual username and password settings set, we connect to Gmail account. Once the account is connected, we request all or unseen emails. If any emails are found, then we can reverse sort the emails so that the newest emails appear on the top.

Now if you attach the above email to an email with the message text in plain text and HTML, imap_fetchbody() will use this type of part number system:

(empty) - Entire message
0 - Message header
1 - MULTIPART/ALTERNATIVE
1.1 - TEXT/PLAIN
1.2 - TEXT/HTML
2 - MESSAGE/RFC822 (entire attached message)
2.0 - Attached message header
2.1 - TEXT/PLAIN
2.2 - TEXT/HTML
2.3 - file.ext

One thought on “Read Gmail Emails using PHP & IMAP”

  1. can you help me with notification of mail using imap
    var notifier = require(‘mail-notifier’);
    var imap = {
    username: “axxxxx@gmail.com”,
    password: “xxxxxxxxxxxx”,
    host: “imap.gmail.com”,
    port: 993, // imap port
    secure: true // use secure connection
    };

    notifier(imap).on(‘mail’,function(mail){console.log(mail);}).start();

    getting error

    Parse error: syntax error, unexpected ‘var’ (T_VAR), expecting end of file in C:\xampp\htdocs\PHPIMAP\admin\index.php on line 146

Leave a Reply

Your email address will not be published. Required fields are marked *