Get emails from gmail using PHP

In this tutorial am going to explain how to get the unread mails from your gmail account using gmail feed atom in PHP. This method using the cURL to fetch the emails from Gmail server through feed atom. XML response will return and we can convert it to HTML.

How to get emails from Gmail Inbox in PHP.

Before starting with this example you need to make sure that cURL function is enabled in your server, if not you can enable that in php setting file called php.ini. if you don’t have access for php.ini, contact your domain administrator and enable it.

Demo Download

First create a function for fetch gmail unread email

//fucntion to get unread emails using username and password from function values
function check_email($username, $password)
{ 
    //Connect Gmail feed atom
    $url = "https://mail.google.com/mail/feed/atom"; 

    // Send Request to read email 
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($curl, CURLOPT_ENCODING, "");
    $curlData = curl_exec($curl);
    curl_close($curl);
	
    //returning retrieved feed
    return $curlData;
}

Now we can call this function with username and password as parameter.

$feed = check_email("YOUR EMAIL ADDRESS", "PASSWORD");

This will return the XML result. now we can display it as HTML. Now we can insert the email to your database also.

$x = new SimpleXmlElement($feed);
echo "<ul>";
foreach($x->entry as $entry)
{
	echo '<li><p><strong>'. $entry->title.'</strong><br>';
	echo $entry->summary;
	echo '</p></li>';
}
echo "</ul>";

That all.. You have done !! Upload and test. Hope that you will enjoy this post.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>