-1

How can I copy email from Gmail to my server's /home/email directory after connecting to a Gmail mailbox using PHP's IMAP functionality?

I want to retrieve every email as a file in MIME format and I want to download the complete MIME file with PHP, not just the body or header of the email. Because of this, imap_fetchbody and imap_fetchheader can't do the job.

Also, it seems imap_mail_copy and imap_mail_move can't do the job because they are designed to copy / move email to mailboxes:

  • imap_mail_copy: Copy specified messages to a mailbox.
  • imap_mail_move: Move specified messages to a mailbox.
Grokify
  • 15,092
  • 6
  • 60
  • 81
showkey
  • 482
  • 42
  • 140
  • 295
  • Use a tool such as 'fetchmail', which is designed to download over imap to a local mail store. – Max Jun 18 '15 at 03:33
  • l like code more than tool, code can make tool. – showkey Jun 18 '15 at 04:33
  • It can, but there's a ready made free software tool that already exists, and you could see how that tool is implemented. PHP is really not the tool for this. – Max Jun 18 '15 at 14:10

1 Answers1

2

PHP will download the full MIME message from Gmail or any IMAP server using imap_fetchbody when the $section parameter is set to "". This will have imap_fetchbody retrieve the entire MIME message including headers and all body parts.

Short example

$mime = imap_fetchbody($stream, $email_id, "");

Long example

// Create IMAP Stream

$mailbox = array(
    'mailbox'  => '{imap.gmail.com:993/imap/ssl}INBOX',
    'username' => 'my_gmail_username',
    'password' => 'my_gmail_password'
);

$stream = imap_open($mailbox['mailbox'], $mailbox['username'], $mailbox['password'])
    or die('Cannot connect to mailbox: ' . imap_last_error());

if (!$stream) {
    echo "Cannot connect to mailbox\n";
} else {

    // Get last week's messages
    $emails = imap_search($stream, 'SINCE '. date('d-M-Y',strtotime("-1 week")));

    if (!count($emails)){
        echo "No emails found\n";
    } else {
        foreach($emails as $email_id) {
            // Use "" for section to retrieve entire MIME message
            $mime = imap_fetchbody($stream, $email_id, "");
            file_put_contents("email_{$email_id}.eml", $mime);
        }
    }

    // Close our imap stream.
    imap_close($stream);
}
Grokify
  • 15,092
  • 6
  • 60
  • 81