How to get emails using PHP and IMAP ?
Last Updated :
15 Oct, 2020
Reading emails from the Gmail account using PHP will be an enriching task for web developers for its simplicity of code through IMAP (Internet Message Access Protocol). Sometimes there can be a requirement in web projects or from a client that needs the complete management of inbox emails or access to email contents from his Gmail account. This feature can also be useful in email marketing or email newsletters that will be sent automatically on a particular schedule. So while researching Gmail account access, one should try listing emails from the Gmail account using PHP and its IMAP functions extension.
IMAP is an internet standard protocol used by clients to get emails from a mail server over a TCP/IP connection with SSL security. The IMAP extension available in PHP libraries provides efficient processing of its email structure and access to email messages via communicating with the email servers.
We use PHP code to connect to the Gmail server and use standard IMAP functions to open up the Gmail account and access or fetch emails based on certain criteria.
Basic requirements: The following are needed for the development of the functionality.
- PHP5 or latest PHP version.
- Enable the IMAP Extension in PHP installation.
- In Gmail account settings, IMAP should be enabled.
Steps to Enable IMAP in XAMPP:
- Go to php.ini configuration file
- Search for ";extension=php_imap.dll"
- Remove the beginning of semicolon and it should be "extension=php_imap.dll"
- Also edit max_execution_time = 4000
Steps to Enable IMAP in Gmail Account:
- Open Gmail.
- Click Settings.
- Select the Forwarding and POP/IMAP blue tab.
- Select "IMAP Access:" section and Enable IMAP radio button.
- Click Save Changes.
- Don't forget to turn on access for less secure apps for Gmail account.
Note: For normal applications, an IMAP server listens on 143 port number.
PHP Code: The following is the HTML and PHP code to list emails from Gmail account. To connect to Gmail, the developer needs the individual's "username" and "password" to be set in the code. Once connected, we search for all emails or emails based on certain criteria by using the imap_search() function. The emails are sorted in a reverse manner so that the latest mails are available on the top using the PHP rsort() function. This PHP function sorts an array in descending order. For every email returned, the subject, from, partial content, and date-time messages are captured. The imap_fetchbody() function fetches a particular section of the email body. So to get the plain text part of the email, we can use "1.1" option as the third parameter.
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href=
"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="style.css">
<script>
function getEmails() {
document.getElementById('dataDivID')
.style.display = "block";
}
</script>
</head>
<body>
<h2>List Emails from Gmail using PHP and IMAP</h2>
<div id="btnContainer">
<button class="btn active" onclick="getEmails()">
<i class="fa fa-bars"></i>Click to get gmail mails
</button>
</div>
<br>
<div id="dataDivID" class="form-container" style="display:none;">
<?php
/* gmail connection,with port number 993 */
$host = '{imap.gmail.com:993/imap/ssl/
novalidate-cert/norsh}INBOX';
/* Your gmail credentials */
$user = '[email protected]';
$password = 'YOUR-PASSWORD';
/* Establish a IMAP connection */
$conn = imap_open($host, $user, $password)
or die('unable to connect Gmail: ' . imap_last_error());
/* Search emails from gmail inbox*/
$mails = imap_search($conn, 'SUBJECT "Comment"');
/* loop through each email id mails are available. */
if ($mails) {
/* Mail output variable starts*/
$mailOutput = '';
$mailOutput.= '<table><tr><th>Subject </th><th> From </th>
<th> Date Time </th> <th> Content </th></tr>';
/* rsort is used to display the latest emails on top */
rsort($mails);
/* For each email */
foreach ($mails as $email_number) {
/* Retrieve specific email information*/
$headers = imap_fetch_overview($conn, $email_number, 0);
/* Returns a particular section of the body*/
$message = imap_fetchbody($conn, $email_number, '1');
$subMessage = substr($message, 0, 150);
$finalMessage = trim(quoted_printable_decode($subMessage));
$mailOutput.= '<div class="row">';
/* Gmail MAILS header information */
$mailOutput.= '<td><span class="columnClass">' .
$headers[0]->subject . '</span></td> ';
$mailOutput.= '<td><span class="columnClass">' .
$headers[0]->from . '</span></td>';
$mailOutput.= '<td><span class="columnClass">' .
$headers[0]->date . '</span></td>';
$mailOutput.= '</div>';
/* Mail body is returned */
$mailOutput.= '<td><span class="column">' .
$finalMessage . '</span></td></tr></div>';
}// End foreach
$mailOutput.= '</table>';
echo $mailOutput;
}//endif
/* imap connection is closed */
imap_close($conn);
?>
</div>
</body>
</html>
CSS code: The following is the code for the file "style.css" used in the above code.
CSS
body {
font-family: Arial;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
tr:nth-child(even) {
background-color: #dddddd;
}
td, th {
padding: 8px;
width:100px;
border: 1px solid #dddddd;
text-align: left;
}
.form-container {
padding: 20px;
background: #F0F0F0;
border: #e0dfdf 1px solid;
border-radius: 2px;
}
* {
box-sizing: border-box;
}
.columnClass {
float: left;
padding: 10px;
}
.row:after {
content: "";
display: table;
clear: both;
}
.btn {
background: #333;
border: #1d1d1d 1px solid;
color: #f0f0f0;
font-size: 0.9em;
width: 200px;
border-radius: 2px;
background-color: #f1f1f1;
cursor: pointer;
}
.btn:hover {
background-color: #ddd;
}
.btn.active {
background-color: #666;
color: white;
}
Output: The following is the output shown for emails retrieved with subject "Comment".
Similar Reads
How to get form data using POST method in PHP ? PHP provides a way to read raw POST data of an HTML Form using php:// which is used for accessing PHPâs input and output streams. In this article, we will use the mentioned way in three different ways. We will use php://input, which is a read-only PHP stream. We will create a basic HTML form page wh
2 min read
How to find email in database using Ajax ? In this article, we will learn how to find an email in a database using Ajax. The jQuery ajax() method uses asynchronous HTTP requests to connect with the server. Here we will use a Node.js server and a MongoDB database. Let's understand using step-by-step implementation. Step 1: Create a folder na
3 min read
How to extract the user name from the email ID using PHP ? Given a string email address, extract the username. Input: â[email protected]â Output: priyank Input: â[email protected]â Output: princepriyank Approach 1: Using PHP strstr() to extract the username from the email address. In this, â@â symbol is the separator for the domain name and user name of
2 min read
How to Send Email using Mailgun API in Node.js ? Sending an email is an essential part of any project and it can be achieved by using Mailgun API. It is very popular for sending emails. Features of Mailgun: . It is easy to get started and easy to use.It is a widely used and popular module for sending emails.Mails can also be scheduled. Installati
2 min read
How to Send Email using NodeJS? Sending emails programmatically is a common requirement in many applications, especially for user notifications, order confirmations, password resets, and newsletters. In this article, we will learn how to build a simple email-sending system using NodeJS. We will use Nodemailer, a popular module for
5 min read