如何使用IMAP和php下载邮件附件到特定文件夹

时间:2012-04-02 09:59:03

标签: php cron imap email-attachments

我正在开发一个网站,用户可以在其中邮寄门票并将任何类型的文件附加到特定的邮件ID。我需要将邮件主题,内容和附件添加到数据库中。我是用cron做的。除了附件,每件事都很完美。我看过一些创建下载链接的帖子。由于我使用的是cron,我无法手动完成。

        $hostname = '{xxxx.net:143/novalidate-cert}INBOX';
        $username = 'yyy@xxxx.net';
        $password = 'zzzz';
        /* try to connect */
        $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to : ' . imap_last_error());
        $emails = imap_search($inbox,'ALL');

                if($emails) {
          $output = '';
          rsort($emails);
          foreach($emails as $email_number) {
            $structure = imap_fetchstructure($inbox, $email_number); 
            $name = $structure->parts[1]->dparameters[0]->value; // name of the file
            $type = $structure->parts[1]->type; //type of the file 
}}

我能够获取文件的类型和名称,但不知道如何继续进行

任何人请帮助我。谢谢......

3 个答案:

答案 0 :(得分:7)

要将附件保存为文件,您需要解析消息的结构,并自行取出作为附件的所有部分(内容处置)。你应该把它包装成自己的类,这样你就可以轻松访问,随着时间的推移你可以更容易地处理错误,电子邮件解析可能很脆弱:

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

这些类的代码或多或少地包含imap_...函数,但对于附件类,它也在对结构进行解析。 You find the code on github。希望这有用。

答案 1 :(得分:5)

虽然使用PHP + Cron和标准邮件服务器可能会起作用,但处理所有边缘情况,错误报告等所需的工作量可能不值得花时间。虽然我没有使用它,Postmark Inbound似乎是一种令人难以置信的(付费)服务,它将消除通过PHP imap api处理电子邮件的大部分麻烦。

如果您想尝试通过PHP处理所有内容,可能需要检查this resource

答案 2 :(得分:0)

如果您要以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。希望这有用。