PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 17.4 Reading Mail with IMAP or POP3

17.4.1 Problem

You want to read mail using IMAP or POP3, which allows you to create a web-based email client.

17.4.2 Solution

Use PHP's IMAP extension, which speaks both IMAP and POP3:

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

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.

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    Chapter 4. Arrays
    Chapter 5. Variables
    Chapter 6. Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    17.1 Introduction
    Recipe 17.2 Sending Mail
    Recipe 17.3 Sending MIME Mail
    Recipe 17.4 Reading Mail with IMAP or POP3
    Recipe 17.5 Posting Messages to Usenet Newsgroups
    Recipe 17.6 Reading Usenet News Messages
    Recipe 17.7 Getting and Putting Files with FTP
    Recipe 17.8 Looking Up Addresses with LDAP
    Recipe 17.9 Using LDAP for User Authentication
    Recipe 17.10 Performing DNS Lookups
    Recipe 17.11 Checking if a Host Is Alive
    Recipe 17.12 Getting Information About a Domain Name
    Chapter 18. Files
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele