How to get raw email data with the imap extension?

10,478

Solution 1

My answer is "overcomplete", see Boy Baukema's answer for a more straight forward "view source" way of doing if you don't need the whole structure of the email.

If you want to fetch all, you need to fetch

As mime-message can have multiple bodies, you need to process each part after the other. To reduce load to the server use the FT_PREFETCHTEXT option for imap_fetchheader. Some example code about imap_fetchstructure in another answer that shows handling the imap connection and iterating over parts of a message already through encapsulation.

Solution 2

I came across this question when I was searching for the same issue. I knew it had to be easier than the solution by hakre and I found the right answer on the page for imap_fetchbody on a post from 5 years ago.

To get the full raw message just use the following:

$imap_stream = imap_open($server, $username, $password);
$raw_full_email = imap_fetchbody($imap_stream, $msg_num, "");

Notice the empty string as third parameter of imap_fetchbody this signifies all parts and sub-parts of the email, including headers and all bodies.

Solution 3

The answer by hakre is overcomplete, if you don't really care about the structure then you won't need imap_fetchstructure.

For a simple 'Show Source' you should only need imap_fetchheader and imap_body.

Example:

$conn = imap_open('{'."$mailServer:$port/pop3}INBOX", $userName, $password, OP_SILENT && OP_READONLY);
$msgs = imap_fetch_overview($conn, '1:5'); /** first 5 messages */
foreach ($msgs as $msg) {
    $source = imap_fetchheader($conn, $msg->msgno) . imap_body($conn, $msg->msgno);
    print $source;
}
Share:
10,478
doni0000
Author by

doni0000

Updated on June 05, 2022

Comments

  • doni0000
    doni0000 about 2 years

    I'm looking for a way to download the whole raw email data (including attachment), similar to what you get by clicking "Show Original" in Gmail.

    Currently, I can get the raw header and some parts of the mail body by this code:

    $this->MailBox = imap_open($mailServer, $userName, $password, OP_SILENT);
    ...
    $email->RawEmail = imap_fetchbody($this->MailBox, $msgNo, "0");
    $email->RawEmail .= "\n".imap_fetchbody($this->MailBox, $msgNo, "1");
    

    Also I know that changing the 3rd parameter of imap_fetchbody might return the encoded attachment. Guess I need a loop here to get the raw email part by part, but what's the condition to stop the loop?

    Is there an easy way to get the whole email at once?

    Any help would be appreciated.