how to download mails attachment to a specific folder using IMAP and php(如何使用 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 将邮件附件下载到特定文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 IMAP 和 php 将邮件附件下载到特定文件夹
基础教程推荐
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01