如何使用IMAP和php将邮件附件下载到特定文件夹 [英] how to download mails attachment to a specific folder using IMAP and php

查看:767
本文介绍了如何使用IMAP和php将邮件附件下载到特定文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个网站,用户可以在其中发送票证,并将任何类型的文件附加到特定的邮件ID。我需要添加邮件主题,内容和附件到数据库。我使用cron这样做。除了附件,每件事情都是完美的。我看到一些创建下载链接的帖子。因为我使用cron我不能手动。

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 database. I am doing this using cron. Except the attachments every thing works perfect. I have seen some post which create download links. Since i am using cron i can't do it manually.

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

我可以获取类型和名称该文件,但不知道如何继续进行

I am able to get type and name of the files but don't know how to proceed further

任何一个请帮助我。谢谢...

Any one please help me. thank you...

推荐答案

要将附件保存为文件,您需要解析邮件的结构,它是它自己的附件(内容部署)。你应该把它包装成自己的类,所以你有一个容易访问,你可以更容易地处理错误,电子邮件解析可能是脆弱的:

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

或多或少地包装 imap _... 函数,但对于附件类,它也在做结构的解析。 您可以在github上找到代码。希望这是有帮助的。

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.

这篇关于如何使用IMAP和php将邮件附件下载到特定文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆