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

后端 未结 3 511
感动是毒
感动是毒 2020-12-23 18:18

i am developing a site in which users can mail tickets and attach any type of files to a specific mail id. I need to add the mail subject, content and attachment to the data

3条回答
  •  隐瞒了意图╮
    2020-12-23 19:04

    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.

提交回复
热议问题