Reading mail from PHP

Active3 hr before
Viewed126 times

9 Answers


PHP Error Messages ,You can connect to an email inbox using PHP’s IMAP functions. First, you need to open an IMAP stream to a mailbox.,$header->Size: The message size,$header->udate: Mail message date in Unix time

1. Open IMAP Stream: imap_open()

$inbox = imap_open($mailbox, $username, $password) or die('Cannot connect to email: '.imap_last_error());
load more v

I currently use the SwiftMailer library to send email, but unfortunately it's only for sending, not receiving. I'm wondering... is there a similar library to connect via IMAP to an email account and read the email (IE give me the ability to loop through email). I'm aware there are a set of PHP IMAP functions located here:,But my question is, does anybody know of an alternative libarary or IMAP wrapper class for receiving/viewing all your emails?, Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers , What kind of systems do we need to coarse-grain to observe interesting phenomena?

Reading Emails with PHP

< ? php

class Email_reader {

   // imap server connection
   public $conn;

   // inbox storage and inbox message count
   private $inbox;
   private $msg_cnt;

   // email login credentials
   private $server = '';
   private $user = '';
   private $pass = 'yourpassword';
   private $port = 143; // adjust according to server settings

   // connect to the server and get the inbox emails
   function __construct() {
      $this - > connect();
      $this - > inbox();

   // close the server connection
   function close() {
      $this - > inbox = array();
      $this - > msg_cnt = 0;

      imap_close($this - > conn);

   // open the server connection
   // the imap_open function parameters will need to be changed for the particular server
   // these are laid out to connect to a Dreamhost IMAP server
   function connect() {
      $this - > conn = imap_open('{'.$this - > server.
         '/notls}', $this - > user, $this - > pass);

   // move the message to a new folder
   function move($msg_index, $folder = 'INBOX.Processed') {
      // move on server
      imap_mail_move($this - > conn, $msg_index, $folder);
      imap_expunge($this - > conn);

      // re-read the inbox
      $this - > inbox();

   // get a specific message (1 = first email, 2 = second email, etc.)
   function get($msg_index = NULL) {
      if (count($this - > inbox) <= 0) {
         return array();
      elseif(!is_null($msg_index) && isset($this - > inbox[$msg_index])) {
         return $this - > inbox[$msg_index];

      return $this - > inbox[0];

   // read the inbox
   function inbox() {
      $this - > msg_cnt = imap_num_msg($this - > conn);

      $in = array();
      for ($i = 1; $i <= $this - > msg_cnt; $i++) {
         $in[] = array(
            'index' => $i,
            'header' => imap_headerinfo($this - > conn, $i),
            'body' => imap_body($this - > conn, $i),
            'structure' => imap_fetchstructure($this - > conn, $i)

      $this - > inbox = $in;



You want to read mail using IMAP or POP3, which allows you to create a web-based email client. ,Use PHP's IMAP extension, which speaks both IMAP and POP3: ,This returns an array in which each element is a formatted string corresponding to a message: ,However, the basics of talking with a mail server are straightforward. Like many features in PHP, you begin by opening the connection and grabbing a handle:

// open IMAP connection
$mail = imap_open('{}', 'username', 'password');
// or, open POP3 connection
$mail = imap_open('{}', 'username', 'password');

// grab a list of all the mail headers
$headers = imap_headers($mail);

// grab a header object for the last message in the mailbox
$last = imap_num_msg($mail);
$header = imap_header($mail, $last);

// grab the body for the same message
$body = imap_body($mail, $last);

// close the connection
load more v

// use this library ->

? php
use PHPMailer\ PHPMailer\ PHPMailer;
use PHPMailer\ PHPMailer\ SMTP;
use PHPMailer\ PHPMailer\ Exception;

function sendEmail() {
   require 'phpmailer/vendor/autoload.php';

   //Create an instance; passing `true` enables exceptions
   $mail = new PHPMailer(true);
   $mail - > CharSet = 'UTF-8';
   try {
      $receiver = '';
      $name = 'Name';

      //Server settings
      $mail - > SMTPDebug = 1; //Enable verbose debug output
      $mail - > isSMTP(); //Send using SMTP
      $mail - > Host = 'tls://'; //Set the SMTP server to send through
      $mail - > SMTPAuth = true; //Enable SMTP authentication
      $mail - > Username = ''; //SMTP username
      $mail - > Password = 'PASSWORD'; //SMTP password
      $mail - > SMTPSecure = tls; //Enable implicit TLS encryption
      $mail - > Port = 587; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

      $mail - > From = '';
      $mail - > setFrom('', 'Name');
      $mail - > addAddress($receiver, $name); //Add a recipient

      $mail - > isHTML(true); //Set email format to HTML
      $mail - > Subject = 'Subject';
      $mail - > Body = 'Body';

      $mail - > send();
      echo 'Message has been sent';
   } catch (Exception $e) {
      echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
} ?
load more v

It is safer that along this code you also use another package to safely parse and filter insecure HTML code before you display it to your site users. Read this other article to learn how to process and display HTML securely when it comes from unsafe sources like for instance email messages.,Assuming that you got the whole contents of the message into the $message variable, you can extract the HTML from a message using code similar to the following.,Keep in mind that the HTML sent in a message may contain malicious JavaScript code that can be used to steal cookies and other security problems.,You can download the PHP POP3 class ZIP archive or install it using the composer tool with the instructions from the install page.If you have more questions feel free to post a comment to this article.

One way to process the incoming messages is to configure the local mail server to start a PHP script when a message arrives on a given mailbox.

To achieve this, you need to learn specific details of how to configure your mail server because each mail server works in a different way.

For instance, if you use qmail mail server, you need to setup a .qmail file associated to the e-mail address that you want to handle. The .qmail file must contain the command that will be executed to start the PHP script that will handle the incoming messages.

For instance, if PHP CLI (Command Line Interface) version path is /usr/bin/php , and the path of the PHP script that will process the messages is /home/crm/bin/request.php, the .qmail file must have this line:

/usr/bin / php / home / crm / bin / request.php
load more v

This is a short tutorial on how to connect to an IMAP email inbox using PHP’s imap functions. To keep things simple, I will connect to the inbox and then retrieve any emails that were received in the last week.,We opened an IMAP stream to our inbox. Note that you will have to change the connection details to match your own inbox. It is worth pointing out that 143 is the default port for IMAP and that notls disables any TLS encryption.,We then created our search criteria. In this example, I told the imap_search function to return emails that have been received in the last week. If you want to retrieve all emails that are currently in the inbox, then you will need to set the $search variable to ALL. If you only want to view unread emails, then you can set the $search variable to UNSEEN. It is important to note that the imap_search function returns a boolean FALSE value if no emails exist. In other words, it will not return an empty array.,Finally, we loop through the emails and print out the subject and the sender’s email address. Note that we use FT_PEEK with the imap_fetchbody function because we want to read the email without flagging it as read! You can remove this parameter if you want your PHP script to mark unseen emails as being read.

Let’s take a look at the following example:


//The location of the mailbox.
$mailbox = '{localhost:143/notls}';
//The username / email address that we want to login to.
$username = '[email protected]';
//The password for this email address.
$password = 'mypassword';

//Attempt to connect using the imap_open function.
$imapResource = imap_open($mailbox, $username, $password);

//If the imap_open function returns a boolean FALSE value,
//then we failed to connect.
if($imapResource === false){
    //If it failed, throw an exception that contains
    //the last imap error.
    throw new Exception(imap_last_error());

//If we get to this point, it means that we have successfully
//connected to our mailbox via IMAP.

//Lets get all emails that were received since a given date.
$search = 'SINCE "' . date("j F Y", strtotime("-7 days")) . '"';
$emails = imap_search($imapResource, $search);

//If the $emails variable is not a boolean FALSE value or
//an empty array.
    //Loop through the emails.
    foreach($emails as $email){
        //Fetch an overview of the email.
        $overview = imap_fetch_overview($imapResource, $email);
        $overview = $overview[0];
        //Print out the subject of the email.
        echo '<b>' . htmlentities($overview->subject) . '</b><br>';
        //Print out the sender's email address / from email address.
        echo 'From: ' . $overview->from . '<br><br>';
        //Get the body of the email.
        $message = imap_fetchbody($imapResource, $email, 1, FT_PEEK);


imap_​open ,imap_body — Read the message body, imap_​reopen , imap_​append

load more v

Accessing a mail server and reading messages can be done by the protocols like IMAP, POP. The messages data read from the mail server will be used for listing emails in a mailbox, creating notification alert about unread messages and for many purposes.,In this code, by using PHP IMAP extension the Gmail server is accessed to fetch the email data. The connection is created by sending the access request with the credentials like host, username, password and more.,Open Gmail and go to Settings -> Forwarding and POP/IMAP and enable IMAP access.,Your email address will not be published. Required fields are marked *

//For Windows,
extension = php_imap.dll

//For Linux,
extension =
load more v

Here is a simple PHP script to read the email inbox. This code also contains PHP script to read an outlook inbox mail received from a particular email address.,Please note that the following is achieved through PHP IMAP PROTOCOL Also, this is not a very secure method of doing it. The idea here is to reveal the concept.,Let us know through comments if it was helpful and please share with others.,Good write-up, I am regular visitor of one’s web site, maintain up the nice operate, and It’s going to be a regular visitor for a long time.

  error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
  $incoming_mail_server = ''; 
  //This is an example incoming mail server for Gmail which you can configure to your outlook, check out the manual on Supported IMAP client list below.
  $your_email = ''; // your outlook email ID
  $yourpassword = 'xyz' // your outlook email password
  $mbox   = imap_open("{$incoming_mail_server}", $your_email , $yourpassword )   or  die("can't connect: " . imap_last_error());
  $num = imap_num_msg($mbox); // read total messages in email
  $MC = imap_check($mbox);
  // Fetch an overview for all messages in INBOX
  $result = imap_fetch_overview($mbox,"$num:{$MC->Nmsgs}",0);
  foreach ($result as $overview) {
    echo 'Message no'.$overview->msgno. '<br/>';
           $check = imap_mailboxmsginfo($mbox);
        echo $check->Unread;
        echo $overview->subject;
        echo $overview->body;
    //code to check and display email received from a particular Email address

Other "reading-undefined" queries related to "Reading mail from PHP"