我能够修改下面的代码,以便将电子邮件附件保存在特定文件夹中,并获取附件链接并下载。 到目前为止,一切都有效,如果电子邮件有多个附件,脚本只输出(回显)第一个附件名称和链接,但它会将所有这些保存在服务器文件夹中。
示例:(一个附件 - 工作正常)
附件:attachment_1.jpg
下载链接:下载
示例:(多个附件)
附件:attachment_1.jpg,attachment_2.jpg等。
下载链接:下载1,下载2等。
如何打印电子邮件的所有附件名称?
echo 'Attachment:' . ' ' . $name[0] . '</br>'; ???
见下面的代码。
$structure = imap_fetchstructure($imap, $m);
$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($imap, $m, $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']);
}
}
}
}
foreach ($attachments as $key => $attachment) {
$name = $attachment['name'];
$contents = $attachment['attachment'];
file_put_contents(STYLESHEETPATH . '/email_attachments/' . $name, $contents);
}
$download_link = get_stylesheet_directory_uri() . '/email_attachments/' . $name;
//imap_setflag_full($imap, $i, "\\Seen");
//imap_mail_move($imap, $i, 'Trash');
//print_r($attachment);
echo '</br>From:' . ' ' . $from_email . '</br>';
echo 'To:' . ' ' . $to . '</br>';
if($name){
echo 'Attachment:' . ' ' . $name . '</br>';
echo 'Path Saved: ' . ' ' . STYLESHEETPATH . '/email_attachments/' . $name . '</br>';
echo 'Download Link: ' . ' ' . '<a href="' . $download_link . '"> Download</a>' . '</br>';
}
echo 'Subject:' . ' ' . $subject . '</br></br>';
}
答案 0 :(得分:0)
下面
if($name){
echo 'Attachment:' . ' ' . $name . '</br>';
echo 'Path Saved: ' . ' ' . STYLESHEETPATH . '/email_attachments/' .$name . '</br>';
echo 'Download Link: ' . ' ' . '<a href="' . $download_link . '"> Download</a>' . '</br>';
}
您只打印一个附件(foreach迭代中剩下的最后一个附件),您需要将其包装在foreach中,如
foreach ($attachments as $key => $attachment) {
$name = $attachment['name'];
$contents = $attachment['attachment'];
// Put your code to print here.
}