PHP Internet Services Reading Mail with IMAP or POP3 - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Internet Services Reading Mail with IMAP or POP3 - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript


Post Top Ad

Post Top Ad

Saturday, June 22, 2019

PHP Internet Services Reading Mail with IMAP or POP3

PHP Internet Services

Reading Mail with IMAP or POP3


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:

       // 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


The underlying library PHP uses to support IMAP and POP3 offers a seemingly unending number of features that allow you to essentially write an entire mail client. With all those features, however, comes complexity. In fact, there are currently 73 different functions in PHP beginning with the word imap, and that doesn’t take into account that some also speak POP3 and NNTP.

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:

       $mail = imap_open('{}', 'username', 'password');

This opens an IMAP connection to the server named on port 143. It also passes along a username and password as the second and third arguments.

To open a POP3 connection instead, append /pop3 to the end of the server and port. Because POP3 usually runs on port 110, add :110 after the server name:

       $mail = imap_open('{}', 'username', 'password');

To encrypt your connection with SSL, add /ssl on to the end, just as you did with pop3. You also need to make sure your PHP installation is built with the --with-imapssl configuration option in addition to --with-imap. Also, you need to build the system IMAP library itself with SSL support. If you’re using a self-signed certificate and wish to prevent an attempted validation, also add /novalidate-cert. Finally, most SSL connections talk on either port 993 or 995. All these options can come in any order, so the following is perfectly legal:

       $mail = imap_open('{}',
                                             'username', 'password');

Surrounding a variable with curly braces inside of a double-quoted string, such as {$var}, is a way to tell PHP exactly which variable to interpolate. Therefore, to use interpolated variables in this first parameter to imap_open(), escape the opening {:

       $server = '';
       $port = 993;

       $mail = imap_open("\{$server:$port}", 'username', 'password');

After you’ve opened a connection, you can ask the mail server a variety of questions. To get a listing of all the messages in your inbox, use imap_headers():

       $headers = imap_headers($mail);

This returns an array in which each element is a formatted string corresponding to a message:

       A    189) 5-Aug-2007 Beth Hondl             an invitation (1992 chars)

Alternatively, to retrieve a specific message, use imap_header() and imap_body() to pull the header object and body string:

       $header = imap_header($message_number);
       $body = imap_body($message_number);

The imap_header() function returns an object with many fields. Useful ones include subject, fromaddress, and udate. All the fields are listed in Table.

Table  imap_header() fields from a server



The body element is just a string, but if the message is a multipart message, such as one that contains both an HTML and a plain-text version, $body holds both parts and the MIME lines describing them:

       Content-Type: text/plain; charset=us-ascii
       Content-Transfer-Encoding: 7bit

       Plain-Text Message

       Content-Type: text/html
       Content-Transfer-Encoding: 7bit

       <html>HTML Message</html>

To avoid this, use imap_fetchstructure() in combination with imap_fetchbody() to discover how the body is formatted and to extract just the parts you want:

       // pull the plain text for message $n
       $st = imap_fetchstructure($mail, $n);

       if (!empty($st->parts)) {
            for ($i = 0, $j = count($st->parts); $i < $j; $i++) {
                   $part = $st->parts[$i];
                   if ($part->subtype == 'PLAIN') {
                          $body = imap_fetchbody($mail, $n, $i+1);
       } else {
            $body = imap_body($mail, $n);

If a message has multiple parts, $st->parts holds an array of objects describing them. The part property holds an integer describing the main body MIME type. Lists which numbers go with which MIME types. The subtype property holds the MIME subtype and tells if the part is plain, html, png, or another type, such as octet-stream.

Table  IMAP MIME type values


No comments:

Post a Comment

Post Top Ad