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

查看:31
本文介绍了如何使用 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天全站免登陆