home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomePHP CookbookSearch this book

17.4. Reading Mail with IMAP or POP3

17.4.3. Discussion

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 63 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('{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. Since POP3 usually runs on port 110, add :110 after the server name:

$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-imap-ssl 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('{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 {:

$server = 'mail.server.com';
$port = 993;

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

Once 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-2002 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 17-2 in Section 17.6.

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

------=_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 occurrence, 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. Table 17-1 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 17-1. IMAP MIME type values

Number

MIME type

PHP constant

Description

Examples

0

text

TYPETEXT

Unformatted text

Plain text, HTML, XML

1

multipart

TYPEMULTIPART

Multipart message

Mixed, form data, signed

2

message

TYPEMESSAGE

Encapsulated message

News, HTTP

3

application

TYPEAPPLICATION

Application data

Octet stream, PDF, Zip

4

audio

TYPEAUDIO

Music file

MP3, RealAudio

5

image

TYPEIMAGE

Graphic image

GIF, JPEG, PNG

6

video

TYPEVIDEO

Video clip

MPEG, Quicktime

7

other

TYPEOTHER 

Everything else

VRML models

17.4.4. See Also

Section 17.2 and Section 17.4 for more on sending mail; documentation on imap_open( ) at http://www.php.net/imap_open, imap_header( ) at http://www.php.net/imap-header, imap-body( ) at http://www.php.net/imap-body, and IMAP in general at http://www.php.net/imap.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.