InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

Menu
  • Home
  • Sitemap

Python Programming Language Best Tutorials and Code Examples

Learn Python Right Now!
Home
PHP
Reading Mail with IMAP or POP3 in PHP
PHP

Reading Mail with IMAP or POP3 in PHP

InfinityCoder December 21, 2016

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// open IMAP connection
$mail = imap_open('{mail.server.com:143}', 'username', 'password');
// or, open POP3 connection
$mail = imap_open('{mail.server.com:110/pop3}', '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
imap_close($mail);

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:

1
$mail = imap_open('{mail.server.com:143}', 'username', 'password');

This opens an IMAP connection to the server named mail.server.com 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:

1
$mail = imap_open('{mail.server.com:110/pop3}', '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:

1
2
$mail = imap_open('{mail.server.com:993/novalidate-cert/pop3/ssl}',
                  '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 {:

1
2
3
4
$server = 'mail.server.com';
$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():

1
$headers = imap_headers($mail);

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

1
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:

1
2
$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.

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:

1
2
3
4
5
6
7
8
9
10
11
12
------=_Part_1046_3914492.1008372096119
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
 
Plain-Text Message
 
------=_Part_1046_3914492.1008372096119
Content-Type: text/html
Content-Transfer-Encoding: 7bit
 
<html>HTML Message</html>
------=_Part_1046_3914492.1008372096119--

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:

1
2
3
4
5
6
7
8
9
10
11
12
// 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. Table 16-2 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 16-2. IMAP MIME type values

Number MIME type PHP constant Description Examples
0

1

2

3

4

5

6

7

text

multipart

message

application

audio

image

video

other

TYPETEXT

TYPEMULTIPART

TYPEMESSAGE

TYPEAPPLICATION

TYPEAUDIO

TYPEIMAGE

TYPEVIDEO

TYPEOTHER

Unformatted text

Multipart message

Encapsulated message

Application data

Music file

Graphic image

Video clip

Everything else

Plain text, HTML, XML

Mixed, form data, signed

News, HTTP

Octet stream, PDF, Zip

MP3

GIF, JPEG, PNG

MPEG, Quicktime

VRML models

 

Share
Tweet
Email
Prev Article
Next Article

Related Articles

Validating a Date in PHP
You want to check if a date is valid. For …

Validating a Date in PHP

Keeping Passwords Out of Your Site Files in PHP
You need to use a password to connect to a …

Keeping Passwords Out of Your Site Files in PHP

About The Author

InfinityCoder
InfinityCoder

Leave a Reply

Cancel reply

Recent Tutorials InfinityQuest

  • Adding New Features to bash Using Loadable Built-ins in bash
    Adding New Features to bash Using Loadable …
    June 27, 2017 0
  • Getting to the Bottom of Things in bash
    Getting to the Bottom of Things in …
    June 27, 2017 0

Recent Comments

  • fer on Turning a Dictionary into XML in Python
  • mahesh on Turning a Dictionary into XML in Python

Categories

  • Bash
  • PHP
  • Python
  • Uncategorized

InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

About Us

Start learning your desired programming language with InfinityQuest.com.

On our website you can access any tutorial that you want with video and code examples.

We are very happy and honored that InfinityQuest.com has been listed as a recommended learning website for students.

Popular Tags

binary data python CIDR convert string into datetime python create xml from dict python dictionary into xml python how to create xml with dict in Python how to write binary data in Python IP Address read binary data python tutorial string as date object python string to datetime python

Archives

  • June 2017
  • April 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
Copyright © 2021 InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more
Programming Tutorials | Sitemap