如何不下载/上传已经存在的IMAP消息?

时间:2019-05-14 05:19:51

标签: php email imap

我有一个带循环的脚本,可以从一台服务器下载消息并将其上传到另一台服务器。 如果消息已存在于目标中,我不想浪费在imap_fetchbodyimap_append上的呼叫。 我可以在“ message_not_existing_in_target”中使用某些内容吗?

$source_imap = imap_open(...);
$target_imap = imap_open(...);
...
if (message_not_existing_in_target) {
    $message = imap_fetchbody($source_imap, $i, '', FT_PEEK);
    imap_append($target_imap, $mbox, $message);
}

至少我需要:

$message = imap_fetchbody($source_imap, $i, '', FT_PEEK);
if (message_not_existing_in_target)
    imap_append($target_imap, $mbox, $message);

由于上传往往比下载慢。

我想提及一些IMAP服务,例如Gmail似乎具有自己的内部重复检查功能-它们仅返回TRUE而不实际保存重复的邮件。但是,该邮件需要上传才能被检测为重复邮件,因此效率仍然不高。

1 个答案:

答案 0 :(得分:0)

$sourceImap = imap_open('...');
$targetImap = imap_open('...');

$sourceMessages = $targetMessages = array();

$checkSourceImap = imap_check($sourceImap);
$checkTargetImap = imap_check($targetImap);

if (
    $checkSourceImap !== false &&
    $checkTargetImap !== false
) {
    $sourceImapOverview = imap_fetch_overview($checkSourceImap, "1:{$checkSourceImap->Nmsgs}");
    $targetImapOverview = imap_fetch_overview($checkTargetImap, "1:{$checkTargetImap->Nmsgs}");

    foreach ($sourceImapOverview as $sourceMessage) {
        $sourceMessages[$sourceMessage->msgno] = strtolower(urlencode($sourceMessage->subject) . '_' . urlencode($sourceMessage->from) . '_' . urlencode($sourceMessage->to)) . '_' . $sourceMessage->udate;
    }

    foreach ($targetImapOverview as $targetMessage) {
        $targetMessages[$targetMessage->msgno] = strtolower(urlencode($targetMessage->subject) . '_' . urlencode($targetMessage->from) . '_' . urlencode($targetMessage->to)) . '_' . $targetMessage->udate;
    }

    $newMessages = array_diff($sourceMessages, $targetMessages);

    if (!empty($newMessages)) {
        foreach ($newMessages as $messageNumber => $newMessage) {
            $message = imap_fetchbody($sourceImap, $messageNumber, '', FT_PEEK);
            imap_append($targetImap, $checkTargetImap->Mailbox, $message);
        }
    }
}