我正在尝试创建一段代码,这些代码将进入邮箱并取出特定文件的附件。到目前为止,我只能查看是否有附件或电子邮件中是否有附件。
但是我希望它能够从电子邮件中取出附件,然后将它们保存到指定的目录中。我尝试取出的附件类型是.jpg
我已尝试过一些我在谷歌上发现的不同代码,我一直试图根据我的代码进行定制,但到目前为止,我一直没有成功找到任何正常工作的东西。
我想知道是否有人能够帮我创建一段能够从电子邮件中取出附件并将其存储在目录中的代码。
感谢。
<?php
/* connect to email */
$hostname = '{*****.com:110/pop3}INBOX';
$username = '*****';
$password = '*****';
// try to connect
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to server: ' . imap_last_error());
// grab emails
$emails = imap_search($inbox,'ALL');
// Search for the 39th email, which has an attachment
$count = 39;
// Fetch all the information about an email
$attachment = imap_fetchstructure($inbox, $count);
// find out how may parts the object has
$numparts = count($attachment->parts);
// find if if multipart message
if ($numparts >= 2) {
foreach ($attachment->parts as $part) {
if ($part->disposition == "INLINE") {
// inline message. Show number of lines
printf("Inline message has %s lines<BR>", $part->lines);
} elseif ($part->disposition == "ATTACHMENT") {
// an attachment
echo "Attachment found!";
// print out the file name
echo "Filename: ", $part->dparameters[0]->value;
}
}
}
//}
else {
// only one part so get some useful info
echo "No attachment";
}
imap_close($imap);
?>
答案 0 :(得分:1)
而不是imap_search
我使用imap_check
来检索邮件概述,以下工作。
查看使用imap_check
找到的消息,这就是提取附件的二进制数据的方法:
$mbox = imap_open( . . . . );
$IMAPobj = imap_check($inbox);
$start = $IMAPobj->Nmsgs-30;
$end = $IMAPobj->Nmsgs;
$result = imap_fetch_overview($inbox,"$start:$end",0);
$count = $end;
foreach ($result as $overview) {
$parts = mail_mime_to_array($inbox, $count);
foreach($parts as $part) {
if(@$part['filename'] || @$part['name'] ) {
$partName = $part['filename'] ? $part['filename'] : $part['name'];
echo "Attachment name is " . basename($partName);
echo "\n";
if(preg_match( . . . write here a regex to detect ".jpg" in $partName . . .)) {
echo "Found file! Extracting binary data...";
$fileContents = $part['data'];
file_put_contents("attachment.jpg", $fileContents);
}
}
}
}