1.解析邮件头
# $mailfile为邮件文件路径function parsemail($mailfile){ echo $mailfile.""; if(file_exists($mailfile)){ $fp = fopen($mailfile, "r"); if (!$fp){ die("open mailfile failed!"); }else{ while(($line = chop(fgets($fp,1024))) && $line !== ""){ echo htmlspecialchars($line).""; } } fclose($fp); }else{ echo "file not exists"; }}
2.根据文件名和ino号查找邮件文件
# $mid为inofunction getmailfile($mid,$mailpath){ $newpath = $mailpath."/new/"; $curpath = $mailpath."/cur/"; $newhandle = opendir($newpath); while(($file = readdir($newhandle)) !== false ){ if ($file != "." && $file != ".." && stat($newpath.$file)['ino'] == $mid){ $mailfile = $newpath.$file; } } closedir($newhandle); $curhandle = opendir($curpath); while(($file = readdir($curhandle)) !== false ){ if ($file != "." && $file != ".." && stat($curpath.$file)['ino'] == $mid){ $mailfile = $curpath.$file; } } closedir($curhandle); return $mailfile;}
3.用parsemail函数
function parsemail($mailfile){ $mime = mailparse_msg_parse_file($mailfile); $struct = mailparse_msg_get_structure($mime); foreach ($struct as $x => $y) { $section = mailparse_msg_get_part($mime, $y); $info = mailparse_msg_get_part_data($section); if ($info["content-disposition"] == 'attachment'){ # 附件名编码过的要解码 $filename = Decode_mime($info["content-name"]); ob_start(); mailparse_msg_extract_part_file($section, $mailfile); $content = ob_get_contents(); ob_end_clean(); # 把附件写到临时目录 $fh = fopen("/home/temp/".$filename,"w+"); fwrite($fh, $content); fclose($fh); } } }function Decode_mime($Str){ if( substr_count($Str,'=?')==0 ) return $Str; list($Token,$Charset,$Encoding,$Str,$End) = preg_split('/\?/',$Str,5); $End = preg_replace("/^\=/","",$End); $Token = preg_replace("/\=/","",$Token); $Encoding = strtolower($Encoding); switch($Encoding){ case 'b': $Text = trim(base64_decode($Str)); break; case 'q': $Text = trim(quoted_printable_decode($Str)); } if( substr_count($End,'=?')!=0 ) $End = Decode_mime($End); return iconv($Charset,"utf-8//IGNORE",$Token.$Text.$End);}