Showing posts with label PHP IMAP Functions. Show all posts
Showing posts with label PHP IMAP Functions. Show all posts

Monday, 17 September 2018

Install PHP IMAP on Debian

If you are getting the "Fatal error: Call to undefined function imap_open()" error in PHP when using the IMAP functions then they are not installed with your installation of PHP. This post looks at how to install the PHP IMAP functions on Debian and should also work for Ubuntu/Kubuntu/etc and other Debian derived Linux distros.
I have previously posted about this for CentOS/RHEL/Fedora and have added this post because the command to install PHP IMAP is different for Debian, and I've recently moved from CentOS with PHP 5.1.6 to Debian with PHP 5.2.6.
To install the PHP IMAP extension on Debian, run the following from the command line either as root or using the sudo command:
aptitude install php5-imap
You'll see something along the lines of this:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
Reading task descriptions... Done
The following NEW packages will be installed:
  libc-client2007b{a} mlock{a} php5-imap
0 packages upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
Need to get 841kB of archives. After unpacking 1810kB will be used.
Do you want to continue? [Y/n/?]
Type in "y" and then <enter> and you'll see something along the lines of this:
Writing extended state information... Done
Get:1 http://ftp.nz.debian.org lenny/main mlock 7:2007b~dfsg-4+lenny3 [30.8kB]
Get:2 http://ftp.nz.debian.org lenny/main libc-client2007b 7:2007b~dfsg-4+lenny3 [772kB]
Get:3 http://ftp.nz.debian.org lenny/main php5-imap 5.2.6.dfsg.1-1+lenny2 [38.1kB]
Fetched 841kB in 2s (322kB/s)
Selecting previously deselected package mlock.
(Reading database ... 19854 files and directories currently installed.)
Unpacking mlock (from .../mlock_7%3a2007b~dfsg-4+lenny3_amd64.deb) ...
Selecting previously deselected package libc-client2007b.
Unpacking libc-client2007b (from .../libc-client2007b_7%3a2007b~dfsg-4+lenny3_amd64.deb) ...
Selecting previously deselected package php5-imap.
Unpacking php5-imap (from .../php5-imap_5.2.6.dfsg.1-1+lenny2_amd64.deb) ...
Processing triggers for man-db ...
Setting up mlock (7:2007b~dfsg-4+lenny3) ...
Setting up libc-client2007b (7:2007b~dfsg-4+lenny3) ...
Setting up php5-imap (5.2.6.dfsg.1-1+lenny2) ...
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
Writing extended state information... Done
Reading task descriptions... Done
You'll be able to immediately access the IMAP functions from the command line interface but will need to gracefully restart Apache to access the functions in your web based scripts by running the following either as root or using the sudo command:
apache2ctl graceful
OR
/usr/sbin/apache2ctl graceful
Now you should be able to use the PHP IMAP functions.

Related posts:

Install PHP IMAP on CentOS

If you are getting the "Fatal error: Call to undefined function imap_open()" error in PHP when using the IMAP functions then they are not installed with your installation of PHP. This post looks at how to install the PHP IMAP functions on CentOS and should also work for Red Hat Enterprise Linux (RHEL), Fedora and other derived Linux distros.
To install PHP IMAP on CentOS run the following from the command line:
sudo yum install php-imap
You'll see some output like this:
Loading "installonlyn" plugin
Setting up Install Process
Setting up repositories
Reading repository metadata in from local files
Parsing package install arguments
Resolving Dependencies
--> Populating transaction set with selected packages. Please wait.
---> Package php-imap.i386 0:5.1.6-20.el5_2.1 set to be updated
--> Running transaction check
--> Processing Dependency: libc-client.so.1 for package: php-imap
--> Restarting Dependency Resolution with new changes.
--> Populating transaction set with selected packages. Please wait.
---> Package libc-client.i386 0:2004g-2.2.1 set to be updated
--> Running transaction check

Dependencies Resolved

=============================================================================
 Package                 Arch       Version          Repository        Size
=============================================================================
Installing:
 php-imap                i386       5.1.6-20.el5_2.1  updates            52 k
Installing for dependencies:
 libc-client             i386       2004g-2.2.1      base              516 k

Transaction Summary
=============================================================================
Install      2 Package(s)
Update       0 Package(s)
Remove       0 Package(s)

Total download size: 568 k
Is this ok [y/N]:
At this point type in "y" and press <enter> and then the installation will continue:
Downloading Packages:
(1/2): php-imap-5.1.6-20. 100% |=========================|  52 kB    00:26
(2/2): libc-client-2004g- 100% |=========================| 516 kB    00:08
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing: libc-client                  ######################### [1/2]
  Installing: php-imap                     ######################### [2/2]

Installed: php-imap.i386 0:5.1.6-20.el5_2.1
Dependency Installed: libc-client.i386 0:2004g-2.2.1
Complete!
You'll be able to immediately access the IMAP functions from the command line interface but will need to gracefully restart Apache to access the functions in your web based scripts:
sudo /etc/init.d/httpd graceful
Now you should be able to use the PHP IMAP functions.

Related posts:

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

Deleting messages with PHP IMAP and Gmail

My last PHP post looked at how to delete email messages using PHP's IMAP functions. This is straight forward on a regular POP3 or IMAP mail server but deleting a message when connected to Gmail just removes it from the inbox and it's still available in "All Mail" rather than being moved into the trash. This post looks at how to move an email into Gmail's trash with PHP IMAP.
Using imap_delete will simply remove the message from the inbox but it will still be available in "All Mail" and won't be in the trash:
imap_delete($connection, $msgno);
So instead the email message must be moved into the trash using the imap_mail_move function. The second parameter for this function takes a range/list and not a single message number, so to move $msgno you need to set the range as "$msgno:$msgno" like so:
imap_mail_move($connection, "$msgno:$msgno", '[Google Mail]/Trash');
The actual name of the trash folder will vary depending on the language settings. For example I have Gmail set to using "English (UK)" so the trash folder is actually called the "Bin" and to move messages into it requires this instead:
imap_mail_move($connection, "$msgno:$msgno", '[Google Mail]/Bin');
I've also seen people refer to the bracketed part as [Gmail] instead of [Google Mail] so it would pay to use the imap_list() function to work out exactly what the trash folder is called and assigning it to a variable. An example of doing this can be found in my Open a mailbox other than the INBOX with PHP IMAP post.

Related posts:

Deleting messages with PHP IMAP

I've been writing a series about sending Google Analytics data by email and then processing the emails with PHP's IMAP functions. Once the email has been processed you'll probably want to delete the emails from the mailbox afterwards so this email looks at how to delete emails using PHP's IMAP functions.
Deleting a message is really simple:
imap_delete($connection, $msgno);
where $connection is your already established mailbox connection, and $msgno is the number of the message that should be deleted. See my looping through messages post which shows how you would get the message number by either looping through the messges in the mailbox or using the imap_search function to do a search.
The above function will flag the message to be deleted when connecting to an imap mailbox so you'll either need to then call the imap_expunge function to delete it completely or add the CL_EXPUNGE parameter to the imap_close function when you disconnect.
Using imap_expunge:
imap_expunge($connection);
When calling imap_close:
imap_close($connection, CL_EXPUNGE);
Note that when connecting using POP3 instead of IMAP, the deletion flag is not saved between connections so you need to call imap_expunge during the connection (or use the CL_EXPUNGE flag when disconnecting) to actually purge the messages. With IMAP you could instead expunge them on the next connection instead.
A note on Gmail: imap_delete doesn't delete messages when connecting to a Gmail mailbox, it just removes them from the inbox. My next PHP post on Thursday will look at how to move a Gmail message from the inbox into the trash using Gmail.

Related posts:

Function to extract email attachments using PHP IMAP

This is a supplementary post in my series about having Google Analytics data sent by email and then downloading and parsing the data with PHP. This post simply contains a PHP function for extracting all the attachments of an email using the PHP IMAP functions into an array.

New function

Please note that I have created a newer, better function for extracting email message bodies and their parts so it is better not to use the function on this page any more. The new function is covered in the following posts:

Original function

I will at some point in the future refine this function to put the plain text body, html body and attachments into separate parts of the array but for the present work I simply need to get the attachments from the email and the body can be ignored.
This is slightly modified version of the code used in my earlier "Extracting attachments from an email message using PHP IMAP functions" post. Read that post for a further explanation of what this function is doing and how it works.
The $connection parameter is an already extablished connection to an IMAP or POP mailserver. The $message_number is the number of the message to extract the attachments from.
function extract_attachments($connection, $message_number) {
   
    $attachments = array();
    $structure = imap_fetchstructure($connection, $message_number);
   
    if(isset($structure->parts) && count($structure->parts)) {
   
        for($i = 0; $i < count($structure->parts); $i++) {
   
            $attachments[$i] = array(
                'is_attachment' => false,
                'filename' => '',
                'name' => '',
                'attachment' => ''
            );
           
            if($structure->parts[$i]->ifdparameters) {
                foreach($structure->parts[$i]->dparameters as $object) {
                    if(strtolower($object->attribute) == 'filename') {
                        $attachments[$i]['is_attachment'] = true;
                        $attachments[$i]['filename'] = $object->value;
                    }
                }
            }
           
            if($structure->parts[$i]->ifparameters) {
                foreach($structure->parts[$i]->parameters as $object) {
                    if(strtolower($object->attribute) == 'name') {
                        $attachments[$i]['is_attachment'] = true;
                        $attachments[$i]['name'] = $object->value;
                    }
                }
            }
           
            if($attachments[$i]['is_attachment']) {
                $attachments[$i]['attachment'] = imap_fetchbody($connection, $message_number, $i+1);
                if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
                    $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
                }
                elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
                    $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
                }
            }
           
        }
       
    }
   
    return $attachments;
   
}
Note that not all elements in the array returned are attachments. Loop through the array and check if the 'is_attachment' value is true to know it's an attachment. I would prefer to use the attachment filename as the the index for the attachment but it's possible in email to have multiple attachments with the exact same filename.
An example print_r output for a Google Analytics email might look like this:
Array
(
    [0] => Array
        (
            [is_attachment] => 
            [filename] => 
            [name] => 
            [attachment] => 
        )

    [1] => Array
        (
            [is_attachment] => 1
            [filename] => Analytics_www.electrictoolbox.com_20090108-20090207.tsv
            [name] => Analytics_www.electrictoolbox.com_20090108-20090207.tsv
            [attachment] => ...
        )

)

Related posts:

Extracting attachments from an email message using PHP IMAP functions

This post is part of an ongoing series which aims to show how to extract data from Google Analytics using its scheduled email reports system. I have already looked at how to send Google Analytics data by email, and how to use the PHP IMAP functions to download email. I will also look at using other PHP libraries to download email and attachments, but for now this post looks at how to extract email attachments using the PHP IMAP functions.

PHP email class

Please note I have written a class for extracting parts from email attachments. This can be downloaded from my more recent post: PHP email message class for extracting attachments

Getting the message structure

There are other was to do this - the method presented here is just one of several was of getting the attachments. I will look at other ways to get attachments from email messages in later posts.
After logging in to the IMAP or POP mail server (detailed in my last post in this series about how to use the PHP IMAP functions to download email) use the imap_fetchstructure() function to get the structure of the message.
The following code snippet example uses the connection stored in $connection to download the message structure for the $message_number message in the mailbox (this is a 1 based index of the messages in the mailbox):
$structure = imap_fetchstructure($connection, $message_number);
Assuming all went well we now have an object containing a lot of information about the message. The following is output from print_r for a message sent from Google Analytics containing tab-separated data in an attachment:
stdClass Object
(
    [type] => 1
    [encoding] => 0
    [ifsubtype] => 1
    [subtype] => MIXED
    [ifdescription] => 0
    [ifid] => 0
    [ifdisposition] => 0
    [ifdparameters] => 0
    [ifparameters] => 1
    [parameters] => Array
        (
            [0] => stdClass Object
                (
                    [attribute] => boundary
                    [value] => 00221532c8aca27cf00462632bb7
                )
        )
    [parts] => Array
        (
            [0] => stdClass Object
                (
                    [type] => 0
                    [encoding] => 0
                    [ifsubtype] => 1
                    [subtype] => PLAIN
                    [ifdescription] => 0
                    [ifid] => 0
                    [lines] => 11
                    [bytes] => 737
                    [ifdisposition] => 0
                    [ifdparameters] => 0
                    [ifparameters] => 1
                    [parameters] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [attribute] => charset
                                    [value] => ISO-8859-1
                                )

                            [1] => stdClass Object
                                (
                                    [attribute] => format
                                    [value] => flowed
                                )

                            [2] => stdClass Object
                                (
                                    [attribute] => delsp
                                    [value] => yes
                                )
                        )
                )
            [1] => stdClass Object
                (
                    [type] => 0
                    [encoding] => 3
                    [ifsubtype] => 1
                    [subtype] => TAB-SEPARATED-VALUES
                    [ifdescription] => 0
                    [ifid] => 0
                    [lines] => 111
                    [bytes] => 8674
                    [ifdisposition] => 1
                    [disposition] => attachment
                    [ifdparameters] => 1
                    [dparameters] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [attribute] => filename
                                    [value] => Analytics_www.electrictoolbox.com_20090108-20090207.tsv
                                )
                        )
                    [ifparameters] => 1
                    [parameters] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [attribute] => charset
                                    [value] => US-ASCII
                                )

                            [1] => stdClass Object
                                (
                                    [attribute] => name
                                    [value] => Analytics_www.electrictoolbox.com_20090108-20090207.tsv
                                )
                        )
                )
        )
)

Working out and getting the attachments

The above isn't the easiest to extract the information we need. You can see we need to loop through [parts] and then each part's [parameters] and [dparameters] to get the filename and name for each, downloading the message part using imap_fetchbody() if it is. If the part doesn't have a name then it's not an attachment.
This is achieved with the following code, assigning information to a array called $attachments. The reason 1 is added to $i in the call to imap_fetchbody() is that the parts are zero-based but in the IMAP functions they are one-based.
$attachments = array();
if(isset($structure->parts) && count($structure->parts)) {

 for($i = 0; $i < count($structure->parts); $i++) {

  $attachments[$i] = array(
   'is_attachment' => false,
   'filename' => '',
   'name' => '',
   'attachment' => ''
  );
  
  if($structure->parts[$i]->ifdparameters) {
   foreach($structure->parts[$i]->dparameters as $object) {
    if(strtolower($object->attribute) == 'filename') {
     $attachments[$i]['is_attachment'] = true;
     $attachments[$i]['filename'] = $object->value;
    }
   }
  }
  
  if($structure->parts[$i]->ifparameters) {
   foreach($structure->parts[$i]->parameters as $object) {
    if(strtolower($object->attribute) == 'name') {
     $attachments[$i]['is_attachment'] = true;
     $attachments[$i]['name'] = $object->value;
    }
   }
  }
  
  if($attachments[$i]['is_attachment']) {
   $attachments[$i]['attachment'] = imap_fetchbody($connection, $message_number, $i+1);
   if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
    $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
   }
   elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
    $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
   }
  }
 }
}
The end result of the above code on our example email is the following, with the data truncated for the actual attachment:
Array
(
    [0] => Array
        (
            [is_attachment] => 
            [filename] => 
            [name] => 
            [attachment] => 
        )

    [1] => Array
        (
            [is_attachment] => 1
            [filename] => Analytics_www.electrictoolbox.com_20090108-20090207.tsv
            [name] => Analytics_www.electrictoolbox.com_20090108-20090207.tsv
            [attachment] => ...
        )

)
You can now loop through the $attachments array looking for the appropriate filename to do whatever processing you need to it.

Conclusion & future posts

The PHP IMAP functions allow you to download email and reasonably easily extract the attachments from it using the code examples presented in this post. Future posts in this series will now look at how to parse TSV, CSV and XML data from the Google Analytics reports using PHP, now that I've covered how to download and extract the attachments.
Read about the series here, including a list of all posts in it.

Related posts:

Open a mailbox other than the INBOX with PHP IMAP

This post is part of an on-going series on this blog about connecting to IMAP mailboxes with PHP, ultimately showing how to download and parse reports from Google Analytics. When logging into an IMAP server with PHP the default mailbox is used - usually the INBOX. This post looks at how to list the mailboxes for the IMAP account and then how to connect to one of the other mailboxes.

Listing the mailboxes

The examples in this post will use a Gmail account as an example. In Gmail you can create "Labels" which are displayed as mailboxes when you log in using IMAP.
We need to use the server connection string multiple times when using the PHP IMAP functions to change mailboxes, so it's a good idea to save it as a variable. In the examples below we'll connect to Gmail so the server string would be defined like so (refer to my using PHP IMAP functions to download email from Gmail post for more details):
$server = '{imap.gmail.com:993/ssl}';
Then we connect to the server:
$connection = imap_open($server, $login, $password);
To get a list of mailboxes use the imap_list() function like so:
$mailboxes = imap_list($connection, $server, '*');
The third parameter is a pattern match and the * indicates to return all mailboxes. You could for example just pass '[Google Mail]*' to only show the Gmail mailboxes and not your own custom labels.
Doing print_r($mailboxes) will show something like this:
Array
(
    [0] => {imap.gmail.com:993/ssl}INBOX
    [1] => {imap.gmail.com:993/ssl}Personal
    [2] => {imap.gmail.com:993/ssl}Servers
    [3] => {imap.gmail.com:993/ssl}[Google Mail]/All Mail
    [4] => {imap.gmail.com:993/ssl}[Google Mail]/Bin
    [5] => {imap.gmail.com:993/ssl}[Google Mail]/Drafts
    [6] => {imap.gmail.com:993/ssl}[Google Mail]/Sent Mail
    [7] => {imap.gmail.com:993/ssl}[Google Mail]/Spam
    [8] => {imap.gmail.com:993/ssl}[Google Mail]/Starred
)
In the above example, INBOX is the default inbox, "Personal" and "Servers" are some custom labels I've set up and the rest are Gmail's special mailboxes.
To loop through and display just the names and not the server, you could do something like this, stripping out the server name using str_replace():
foreach($mailboxes as $mailbox) {
    $shortname = str_replace($server, '', $mailbox);
    echo "$shortname\n";
}
and the resulting list would look like this:
INBOX
Personal
Servers
[Google Mail]/All Mail
[Google Mail]/Bin
[Google Mail]/Drafts
[Google Mail]/Sent Mail
[Google Mail]/Spam
[Google Mail]/Starred

Connecting to a mailbox

Use the imap_reopen() function to connect to a different mailbox. You need to pass the already established connection and then the mailbox to connect to. The mailbox name must include the server string. The following example connects to the 'Servers' mailbox:
imap_reopen($connection, $server.'Servers');
You can then use the other IMAP functions to loop through mail in that mailbox and display messages from it. I covered how to loop through a mailbox in an earlier post so the you'd just need to connect to the mailbox and then loop through the messages in the normal way.

Future posts

The next post in this series, this time next week, will look at how to loop through the mailbox looking for a specific message based on the subject. The following two posts will then extract the Google Analytics data from the emails so you could inject into a database etc. I'll then look at other IMAP functions and also some other libraries for connecting to email accounts with PHP. Be sure to subscribe to my RSS feed (details below) so you don't miss out on this series.

Related posts:

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: