how to download mails attachment to a specific folder using IMAP and php

非 Y 不嫁゛ 提交于 2019-11-29 21:08:21

To save attachments as files, you need to parse the structure of the message and take out all parts that are attachments on it's own (content disposition). You should wrap that into classes of their own so you have an easy access and you can handle errors more easily over time, email parsing can be fragile:

$savedir = __DIR__ . '/imap-dump/';

$inbox = new IMAPMailbox($hostname, $username, $password);
$emails = $inbox->search('ALL');
if ($emails) {
    rsort($emails);
    foreach ($emails as $email) {
        foreach ($email->getAttachments() as $attachment) {
            $savepath = $savedir . $attachment->getFilename();
            file_put_contents($savepath, $attachment);
        }
    }
}

The code of these classes is more or less wrapping the imap_... functions, but for the attachment classes, it's doing the parsing of the structures as well. You find the code on github. Hope this is helpful.

Although using PHP + Cron and a standard mail server might work, the amount of work needed to handle all the edge cases, error reporting, etc might not be worth the time. Although I haven't used it, Postmark Inbound seems like an incredible (paid) service that will eliminate most of the headache of processing email via the PHP imap api.

If you want to try to handle everything via PHP, you might want to check this resource out.

In case if you want to download attachments as zip

$zip = new ZipArchive();
$tmp_file = tempnam('.', '');
$zip->open($tmp_file, ZipArchive::CREATE);

$mailbox = $connection->getMailbox('INBOX');
foreach ($mailbox->getMessage() as $message) {
    $attachments = $message->getAttachments();
    foreach ($attachments as $attachment) {
        $zip->addFromString($attachment->getFilename(), $attachment->getDecodedContent());
    }
}

$zip->close();

# send the file to the browser as a download
header('Content-disposition: attachment; filename=download.zip');
header('Content-type: application/zip');
readfile($tmp_file);

This code uses library hosted on GitHub. Hope this is helpful.

Using the email download manager software, you can download emails with attachments on a specific folder to a computer storage location. The software provides an IMAP server option to access your webmail or mail server account easily.

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