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:
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);
}