How to copy email from Gmail to my server using PHP IMAP?

僤鯓⒐⒋嵵緔 提交于 2020-01-03 06:38:24

问题


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.

回答1:


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


来源:https://stackoverflow.com/questions/30905978/how-to-copy-email-from-gmail-to-my-server-using-php-imap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!