Search code examples
phpoutlookimapexpresseml

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


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,


Solution

  • 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