如何使用PHP IMAP将电子邮件从Gmail复制到我的服务器? [英] How to copy email from Gmail to my server using PHP IMAP?
问题描述
在使用 / home / email 目录中/manual/en/book.imap.phprel =nofollow> PHP的IMAP功能?
我想检索每个电子邮件作为文件MIME格式,我想用PHP下载完整的MIME文件,而不仅仅是电子邮件的正文或标题。因此, imap_fetchbody
和 imap_fetchheader
无法完成这项工作。
此外,似乎 当 时,PHP将使用 简短示例 imap_mail_copy
和 imap_mail_move
无法完成这项工作,因为它们被设计为复制/将电子邮件移至邮箱:
$ section
参数为 imap_fetchbody
从Gmail或任何IMAP服务器下载完整的MIME邮件设置为。这将有
imap_fetchbody
检索包括标题和所有正文部分的整个MIME消息。
$ mime = imap_fetchbody($ stream,$ email_id,);
长示例
//创建IMAP流
$ 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'])
或者die('无法连接邮箱: '。imap_last_error());
if(!$ stream){
echo无法连接邮箱\ n;
} else {
//获取上周的消息
$ emails = imap_search($ stream,'SINCE'。date('dM-Y',strtotime( - 1周)));
if(!count($ emails)){
echo没有找到电子邮件\\\
;
} else {
foreach($ emails as $ email_id){
//使用部分来检索整个MIME消息
$ mime = imap_fetchbody($ stream,$ email_id ,);
file_put_contents(email _ {$ email_id} .eml,$ mime);
}
}
//关闭我们的imap流。
imap_close($ stream);
}
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.
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);
}
这篇关于如何使用PHP IMAP将电子邮件从Gmail复制到我的服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!