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
A common mistake is to use "\n"
or PHP_EOL
.
According to RFC RFC821, RFC2060, RFC1939 "\r\n"
should be used.
While some mailserver auto convert that mistakes, Cyrus does not and throw a nice error.
PHP_EOL
is a system depending constant, it's "\n"
on Linux, "\r"
on Mac and "\r\n"
on Windows, for example.
Furthermore imap_fetchheader()
contains the trailing "\r\n"
as expected. So the correct example would be:
$source = imap_fetchheader($conn, $msg->msgno) . imap_body($conn, $msg->msgno);
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.
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;
}
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.