在 PHP 中使用 IMAP 将附件下载到目录,随机工作
Posted
技术标签:
【中文标题】在 PHP 中使用 IMAP 将附件下载到目录,随机工作【英文标题】:Downloading attachments to directory with IMAP in PHP, randomly works 【发布时间】:2011-02-08 15:01:01 【问题描述】:我在网上找到了 php 代码,可以从这里使用 IMAP 将附件下载到目录。 http://www.nerdydork.com/download-pop3imap-email-attachments-with-php.html
我稍微修改了一下
$structure = imap_fetchstructure($mbox, $jk);
$parts = ($structure->parts);
到
$structure = imap_fetchstructure($mbox, $jk);
$parts = ($structure);
让它正常运行,否则我得到一个关于 stdClass 没有定义名为 $parts 的属性的错误。这样做,我能够下载所有附件。不过最近我又试了一次,还是不行。好吧,它没有工作 6 次,工作了 7 次,然后就没有工作了。我认为这与我搞砸了部件处理有关,因为 count($parts) 一直为每条消息返回 1,所以它没有找到我认为的任何附件。
由于它在某一时刻毫无问题地下载了附件,因此我确信事情正在搞砸的地方就在这里。在此代码块之前是一个 for 循环,它遍历框中的每条消息,之后是一个循环,它只遍历每个 imap 结构的 $parts。感谢您的任何帮助,您可以提供。我查看了 php.net 上的 imap_fetchstructure 页面,无法弄清楚我做错了什么。
编辑:我只是在输入我的问题后仔细检查了文件夹,它全部弹出。我觉得我快疯了。在我开始输入之前的几分钟内,我没有运行代码,对我来说,触发需要这么长时间是没有意义的。我的邮箱中有大约 800 条消息,但我认为它在 PHP 的最后打印了我的声明,所有文件创建工作都已完成。
【问题讨论】:
你需要选择一个答案,尼克。 【参考方案1】:查看此代码:
$structure = imap_fetchstructure($mailbox, $index);
$attachments = array();
if(isset($structure->parts) && count($structure->parts))
for($i = 0; $i < count($structure->parts); $i++)
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => '');
if($structure->parts[$i]->ifdparameters)
foreach($structure->parts[$i]->dparameters as $object)
if(strtolower($object->attribute) == 'filename')
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
if($structure->parts[$i]->ifparameters)
foreach($structure->parts[$i]->parameters as $object)
if(strtolower($object->attribute) == 'name')
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
if($attachments[$i]['is_attachment'])
$attachments[$i]['attachment'] = imap_fetchbody($connection, $message_number, $i+1);
if($structure->parts[$i]->encoding == 3) // 3 = BASE64
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
elseif($structure->parts[$i]->encoding == 4) // 4 = QUOTED-PRINTABLE
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
// for($i = 0; $i < count($structure->parts); $i++)
// if(isset($structure->parts) && count($structure->parts))
【讨论】:
【参考方案2】:这是最终的工作样本
<? include('application.php');
/* connect to gmail */
$hostname = 'imap.gmail.com:993/imap/sslINBOX';
$username = 'XX@XX.com';
$password = 'XX';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox, 'FROM "xxx@gmail.com"');
/* if emails are returned, cycle through each... */
if($emails)
/* begin output var */
$output = '';
/* put the newest emails on top */
rsort($emails);
foreach($emails as $email_number)
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_fetchbody($inbox,$email_number,2);
$structure = imap_fetchstructure($inbox,$email_number);
pre($overview);
$attachments = array();
if(isset($structure->parts) && count($structure->parts))
for($i = 0; $i < count($structure->parts); $i++)
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => '');
if($structure->parts[$i]->ifdparameters)
foreach($structure->parts[$i]->dparameters as $object)
if(strtolower($object->attribute) == 'filename')
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
if($structure->parts[$i]->ifparameters)
foreach($structure->parts[$i]->parameters as $object)
if(strtolower($object->attribute) == 'name')
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
if($attachments[$i]['is_attachment'])
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);
if($structure->parts[$i]->encoding == 3) // 3 = BASE64
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
elseif($structure->parts[$i]->encoding == 4) // 4 = QUOTED-PRINTABLE
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
// for($i = 0; $i < count($structure->parts); $i++)
// if(isset($structure->parts) && count($structure->parts))
if(count($attachments)!=0)
foreach($attachments as $at)
if($at['is_attachment']==1)
file_put_contents($at['filename'], $at['attachment']);
// echo $output;
/* close the connection */
imap_close($inbox);
?>
【讨论】:
我试过了,"$attachments[$i]['attachment']" 在 imap_fetchbody($inbox, $email_number, $i+1) 之后总是为空 - 数组中有名称,但附件键中没有内容。为什么? 能否提供您使用的 imap 类的链接【参考方案3】:这是完美的工作答案,试试这个。
此示例运行正常,下载所有附件都没有问题。
<?php
set_time_limit(3000);
/* connect to gmail with your credentials */
$hostname = 'imap.gmail.com:993/imap/sslINBOX';
$username = 'YOUR_USERNAME';
$password = 'YOUR_PASSWORD';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
$emails = imap_search($inbox, 'FROM "abc@gmail.com"');
/* if any emails found, iterate through each email */
if($emails)
$count = 1;
/* put the newest emails on top */
rsort($emails);
/* for every email... */
foreach($emails as $email_number)
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_fetchbody($inbox,$email_number,2);
/* get mail structure */
$structure = imap_fetchstructure($inbox, $email_number);
$attachments = array();
/* if any attachments found... */
if(isset($structure->parts) && count($structure->parts))
for($i = 0; $i < count($structure->parts); $i++)
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters)
foreach($structure->parts[$i]->dparameters as $object)
if(strtolower($object->attribute) == 'filename')
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
if($structure->parts[$i]->ifparameters)
foreach($structure->parts[$i]->parameters as $object)
if(strtolower($object->attribute) == 'name')
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
if($attachments[$i]['is_attachment'])
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);
/* 3 = BASE64 encoding */
if($structure->parts[$i]->encoding == 3)
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
/* 4 = QUOTED-PRINTABLE encoding */
elseif($structure->parts[$i]->encoding == 4)
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
/* iterate through each attachment and save it */
foreach($attachments as $attachment)
if($attachment['is_attachment'] == 1)
$filename = $attachment['name'];
if(empty($filename)) $filename = $attachment['filename'];
if(empty($filename)) $filename = time() . ".dat";
$folder = "attachment";
if(!is_dir($folder))
mkdir($folder);
$fp = fopen("./". $folder ."/". $email_number . "-" . $filename, "w+");
fwrite($fp, $attachment['attachment']);
fclose($fp);
/* close the connection */
imap_close($inbox);
echo "all attachment Downloaded";
?>
更多,见链接
http://www.codediesel.com/php/downloading-gmail-attachments-in-php-an-update/
【讨论】:
这对我来说非常有效,这应该是公认的答案。 很高兴帮助@GeorgeGarey 帮助很大! 很高兴@N.Dias【参考方案4】: //may this help you...good luck
date_default_timezone_set('UTC');
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('memory_limit', '-1');
ini_set('max_execution_time', 0);
set_time_limit(3000);
$fName = [];
if ($subject=='xyz subject' || $subject=='xyz subject')$folder_name = $subject;
else$folder_name = substr($subject,stripos($subject,':')+2);
$list = glob('downloads/xyz/'.$folder_name.'/*');
foreach($list as $key => $filename)$explodeName = explode('/', $filename);$fName[] = $explodeName[2];
foreach($list as $file)if(is_file($file))unlink($file);
$hostname = 'imap.gmail.com:993/imap/sslInbox';
$username = 'xyz.xyz@xyz.com';
$password = '*******************';
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
$emails = imap_search($inbox, 'SUBJECT "'.$subject.'"');
foreach ($emails as $key => $value)
$overview = imap_fetch_overview($inbox,$value,0);
$message_date = new DateTime($overview[0]->date);
$date = $message_date->format('Ymd');
$message = imap_fetchbody($inbox,$value,2);
$structure = imap_fetchstructure($inbox, $value);
$attachments = [];
if(isset($structure->parts) && count($structure->parts))
for($i = 0; $i < count($structure->parts); $i++)
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters)
foreach($structure->parts[$i]->dparameters as $object)
if(strtolower($object->attribute) == 'filename')
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
if($structure->parts[$i]->ifparameters)
foreach($structure->parts[$i]->parameters as $object)
if(strtolower($object->attribute) == 'name')
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
if($attachments[$i]['is_attachment'])
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $value, $i+1);
if($structure->parts[$i]->encoding == 3) //3 = BASE64 encoding
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
elseif($structure->parts[$i]->encoding == 4) //4 = QUOTED-PRINTABLE encoding
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
foreach($attachments as $attachment)//iterate through each attachment and save it
if($attachment['is_attachment'] == 1)
$filename = $attachment['name'];
if(empty($filename)) $filename = $attachment['filename'];
if(empty($filename)) $filename = time() . ".dat";
$new_fileName = $date.'-'.$value.'-'.$filename;
if(!in_array($new_fileName, $fName))
$folder='./downloads/xyz/'.$folder_name.'/';
if(!is_dir($folder))mkdir($folder);
$fp = fopen("./". $folder ."/". $date . "-". $value."-". $filename, "w+");
fwrite($fp, $attachment['attachment']);
fclose($fp);
imap_mail_move($inbox,$overview[0]->msgno,'xyz_label');
imap_expunge($inbox);
/* ->Always try to read/open the email by subject/or according to need
->Move or Delete Old/not required mail, so that u don't need to search/load lots of email
->Avoiding unnecessary and old email of the same subject , is to move/delete the same.
*/
imap_close($inbox);//Never forget to close the connection
【讨论】:
【参考方案5】:一些错误修复和对完美工作的答案的改进
$structure = imap_fetchstructure($mailbox, $email_number);
$attachments = [];
foreach ($structure->parts as $part)
$is_attachment = (isset($part->disposition) && $part->disposition == 'ATTACHMENT');
if ($part->ifdparameters)
foreach ($part->dparameters as $object)
if (strtolower($object->attribute) == 'filename')
$is_attachment = true;
$filename = $object->value;
break;
if ($part->ifparameters)
foreach ($part->parameters as $object)
if (strtolower($object->attribute) == 'name')
$is_attachment = true;
$name = $object->value;
break;
if (!$is_attachment)
continue;
$attachment = imap_fetchbody($mailbox, $email_number, $email_number+1);
if ($part->encoding == 3)
$attachment = base64_decode($attachment);
elseif ($part->encoding == 4)
$attachment = quoted_printable_decode($attachment);
$attachments[] = [
'is_attachment' => $is_attachment,
'filename' => isset($filename) ? $filename : '',
'name' => isset($name) ? $name : '',
'attachment' => isset($attachment) ? $attachment : ''
];
/* iterate through each attachment and save it */
$folder = "attachment";
if (!is_dir($folder))
mkdir($folder);
foreach ($attachments as $attachment)
if (!empty($attachment['name']))
$filename = $attachment['name'];
elseif (!empty($attachment['filename']))
$filename = $attachment['filename'];
else
$filename = time().'.dat';
$destination = './'.$folder.'/'.$email_number.'-'.$filename;
file_put_contents($destination, $attachment['attachment']);
count 如果输入是假的,则返回 1(真实),因此您不应该以这种方式在比较中使用它
当你可以使用foreach时,你不需要循环for:让事情变得简单
仅在实际有用时才将新项目添加到数组附件中:添加稍后将在保存时跳过的项目是没有意义的
foreach 循环遍历可迭代对象,如果 count 为 0,则根本不循环:无需在 foreach 之前检查 count
无需分配 $filename 和覆盖:只需通过比较检查,并直接分配正确的值或默认情况
file_put_contents 等同于依次调用fopen()、fwrite() 和fclose() 将数据写入文件
对 $is_attachment 进行更强大的检查
mkdir 文件夹应保持在循环之外,因为文件夹始终相同
【讨论】:
以上是关于在 PHP 中使用 IMAP 将附件下载到目录,随机工作的主要内容,如果未能解决你的问题,请参考以下文章
python和imaplib:如何在给定电子邮件ID的情况下下载附件文件