Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get raw email data with the imap extension?

Tags:

php

email

imap

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.

like image 623
doni0000 Avatar asked Apr 24 '12 07:04

doni0000


3 Answers

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.

like image 193
Gonçalo Baltazar Avatar answered Nov 10 '22 01:11

Gonçalo Baltazar


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;
}
like image 29
Boy Baukema Avatar answered Nov 09 '22 23:11

Boy Baukema


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

  • The headers imap_fetchheader.
  • Obtain the number of bodies the message has imap_fetchstructure.
  • Each mine-headers a body has imap_fetchmime.
  • Each body it has imap_fetchbody.

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.

like image 25
hakre Avatar answered Nov 09 '22 23:11

hakre