Showing posts with label PHP DOWNLOAD Email. Show all posts
Showing posts with label PHP DOWNLOAD Email. Show all posts

Monday, 17 September 2018

Using PHP IMAP functions to download email from Gmail

A couple of weeks back I posted how to use the PHP IMAP functions to download email from an IMAP server. This post looks at how to do the same but downloading IMAP mail from Gmail, which you need to connect to on a different port and use SSL. Earlier today I posted how to enable IMAP mail access in Gmail so you'll need to ensure that's done first.

How to connect to a normal IMAP server

As a quick recap, this is how you connect to an IMAP mail server using PHP, where $server is the name of the IMAP mail server (including {curly brackets} :ports and /flags), $login is your login name and $password is your password:
$connection = imap_open('$server', $login, $password);

How to connect to Gmail's IMAP server

Gmail requires the IMAP connection to be made on port 993 and it must be an SSL connection.The hostname is imap.gmail.com. Therefore, to connect to Gmail IMAP with the PHP IMAP functions you would do this:
$server = '{imap.gmail.com:993/ssl}';
$connection = imap_open($server, $login, $password);
Note that your login name for Gmail includes the domain name as well.
If you have an @gmail.com email address then your login name would be e.g. 'my-email-address@gmail.com'
If you use Google Apps and have your domain mail hosted with Gmail then it will be your account email address e.g. 'chris@example.com'
IMAP supports the concept of multiple mailboxes. In Gmail your labels become mailboxes in your IMAP connection. When you first connect using the above you'll be looking at the INBOX. It is possible to then change to one of your other mailboxes and read mail from there.

How to download the email using IMAP from Gmail

At this stage it's the same as downloading mail from any IMAP server, so refer to my other post which shows how to use the PHP IMAP functions to download email from an IMAP server


Update - novalidate-cert flag

I recently moved from CentOS 5 with PHP 5.1.6 to Debian 5 with PHP 5.2.6 in my development environment (and will also do in production next week). My same test script would no longer connect to Gmail, instead error'ing out with:
Warning: imap_open(): Couldn't open stream {imap.gmail.com:993/ssl}
After various testing of different flags I discovered I needed to add the 'novalidate-cert' flag so the server string looks like this:
$server = '{imap.gmail.com:993/ssl/novalidate-cert}';
The next post in this series will look at how to open other mailboxes with PHP IMAP, using Gmail's mailboxes and labels as an example.

Update - firewall issues

I received an email from Jesse Fisher who was having issues connecting to Gmail with the PHP IMAP functions and was getting the error message "Can't connect to gmail-imap.l.google.com,993: Connection refused".
It turned out that port 993 was blocked by the firewall on the server that the PHP script was running on. Once the hosting provider opened that port the issue went away and Jesse was able to connect.
If you are getting an error like this connecting to a mail server using the PHP IMAP functions then checking the outbound firewall settings is one thing that needs to be looked at.
 

Related posts:

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: