Need to save a copy of email using imap php and then can be open in outlook express

Dell picture Dell · Sep 21, 2011 · Viewed 9.7k times · Source

I had IMAP PHP script which is connecting and reading emails from the mail box.

What i am looking is that i want to save the email on server disk and name it something like testing.eml file. So when later i down those emails and can be viewed in outlook express. Any thoughts how can this be achieved.

Thanks,

Answer

Piskvor left the building picture Piskvor left the building · Sep 21, 2011

See PHP's IMAP reference; here's the core functionality:

$mbox = imap_open ("{localhost:993/imap/ssl}INBOX", "user_id", "password");
$message_count = imap_num_msg($mbox);
if ($message_count > 0) {
    $headers = imap_fetchheader($mbox, $message_count, FT_PREFETCHTEXT);
    $body = imap_body($mbox, $message_count);
    file_put_contents('/your/file/here.eml', $headers . "\n" . $body);
}
imap_close($mbox);

What happens here:

  • open the mailbox
  • get message count
  • if there are any:
    • get headers of the last one
    • get body of the last one
    • save them together in a file
  • close the mailbox