Wednesday, 12 September 2018

Using PHP IMAP functions to download email

This post looks at how to connect to a POP or IMAP mailbox using PHP's IMAP mail functions and retrive the number of messages in the mailbox, the message headers and body, and then to delete the message.

IMAP functions not installed?

If you get the error message "Fatal error: Call to undefined function imap_open()" when trying to connect to the mailbox then the IMAP functions are not installed in your PHP install. I detailed how to install this in an earlier post today for CentOS. Other Linux distibutions will have similar methods for installing the IMAP extension.

Connecting to the mailbox

To connect to a POP3 mail server, do the following, where $server contains the server to connect to, $login and $password the login name and password used to access the mailbox:
$connection = imap_open('{$server:110/pop3}', $login, $password);
If it's an IMAP server you can leave out the port number and slash part:
$connection = imap_open('{$server}', $login, $password);
The value returned will either be an IMAP resource or boolean false in the event of an error.
Note that if you're getting "Warning: imap_open(): Couldn't open stream" type of errors when connecting you may need to append the /notls flag after the server e.g.:
$connection = imap_open('{$server/notls}', $login, $password);
I found that I needed to do this when moving a script from CentOS with PHP 5.1.6 to Debian with PHP 5.2.6. On Debian it would give the error unless I had the "notls" flag. Obviously if you need tls or ssl then you'd add those flags instead of notls.

Get the number of messages

To get the number of messages in the mailbox use the imap_num_msg() function like so:
$count = imap_num_msg($connection);

Loop through and retrieve the messages

Use a simple loop to loop through from 1 to the number of messages combined with the imap_headerinfo and imap_body functions to get the message headers formatted into an object and the raw body respectively.
for($i = 1; $i <= $count; $i++) {
    $header = imap_headerinfo($connection, $i);
    $raw_body = imap_body($connection, $i);
}
Note that the imap_body() function returns the raw body of the email messages, which also contains all the mime parts and attachments etc (if present), not just the plain text message. I will deal with looking at the parts of an email message in next Monday's PHP post.

Header object

The value returned from the imap_headerinfo() function is an object containing a number of properties. To show the values available, an example of the output from print_r is as follows:
stdClass Object
(
    [date] => Wed, 4 Feb 2009 22:37:42 +1300
    [Date] => Wed, 4 Feb 2009 22:37:42 +1300
    [subject] => Fwd: another test
    [Subject] => Fwd: another test
    [in_reply_to] => <59f89e00902040137vb73ed1ep5f870dafe02f26cf@mail.example.com>
    [message_id] => <59f89e00902040137s16c317b6oa4658a4d2cc64c3c@mail.example.com>
    [references] => <59f89e00902040137vb73ed1ep5f870dafe02f26cf@mail.example.com>
    [toaddress] => john@example.com
    [to] => Array
        (
            [0] => stdClass Object
                (
                    [mailbox] => john
                    [host] => example.com
                )

        )

    [fromaddress] => Chris Hope 
    [from] => Array
        (
            [0] => stdClass Object
                (
                    [personal] => Chris Hope
                    [mailbox] => chris
                    [host] => example.com
                )

        )

    [reply_toaddress] => Chris Hope 
    [reply_to] => Array
        (
            [0] => stdClass Object
                (
                    [personal] => Chris Hope
                    [mailbox] => chris
                    [host] => example.com
                )

        )

    [senderaddress] => Chris Hope 
    [sender] => Array
        (
            [0] => stdClass Object
                (
                    [personal] => Chris Hope
                    [mailbox] => chris
                    [host] => example.com
                )

        )

    [Recent] => N
    [Unseen] =>  
    [Flagged] =>  
    [Answered] =>  
    [Deleted] =>  
    [Draft] =>  
    [Msgno] =>   20
    [MailDate] =>  4-Feb-2009 22:37:42 +1300
    [Size] => 3111
    [udate] => 1233740262
)

Future posts

In Monday's post I will look at ways to get the parts of the email body instead of just the raw email message. This is a lead-up to extracting email attachments from an email message, which is required for my future post about automatically handling emails from Google Analytics to update statistical data for your website or reporting purposes, as mentioned in Sunday's "Sending Google Analytics Reports Regularly by Email" post.
Make sure you subscribe to my RSS feed (details below) so you don't miss out on future posts in this series. Read about the series here.

Related posts:

0 comments:

Post a Comment