邮件附件
我似乎无法找到我写这个PHP函数的问题,应该发送附件的电子邮件。 我一直在努力挣扎。
function myMail($to, $subject, $mail_msg, $filename, $contentType){
$random_hash = md5(date('r', time()));
$headers = "From: webmaster@example.comrnReply-To: ".$to;
$headers .= "rnContent-Type: ".$contentType.
"; boundary="PHP-mixed-".$random_hash.""";
$attachment = chunk_split(base64_encode(file_get_contents($filename)));
ob_start();
echo "
--PHP-mixed-$random_hash
Content-Type: multipart/alternative; boundary="PHP-alt-$random_hash"
--PHP-alt-$random_hash
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
$mail_msg
--PHP-alt-$random_hash
--PHP-mixed-$random_hash--
Content-Type: text/plain; name="$filename"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--PHP-mixed-$random_hash--
";
$message = ob_get_clean();
$mail_sent = @mail( $to, $subject, $message, $headers );
return $mail_sent ? "Mail sent" : "Mail failed";
}
编辑问题是邮件的邮件与文件混合并作为附件发送。
我刚刚看了几封电子邮件,我注意到最终附件边界以' - '结尾,而开始边界标记没有。 在你的代码中,你有:
--PHP-mixed-$random_hash--
Content-Type: text/plain; name="$filename"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--PHP-mixed-$random_hash--
也许它应该是:
--PHP-mixed-$random_hash
Content-Type: text/plain; name="$filename"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--PHP-mixed-$random_hash--
看看这里的例子:
http://en.wikipedia.org/wiki/MIME#Multipart_messages
Artefacto让我更加关注输出,并且找到了解决方法:
function myMail($to, $subject, $mail_msg, $filename, $contentType, $pathToFilename){ $random_hash = md5(date('r', time())); $headers = "From: webmaster@mysite.comrnReply-To: ".$to; $headers .= "rnContent-Type: multipart/mixed; boundary="PHP-mixed-".$random_hash."""; $attachment = chunk_split(base64_encode(file_get_contents($pathToFilename))); ob_start(); echo " --PHP-mixed-$random_hash Content-Type: multipart/alternative; boundary="PHP-alt-$random_hash" --PHP-alt-$random_hash Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit $mail_msg --PHP-alt-$random_hash-- --PHP-mixed-$random_hash Content-Type: $contentType; name="$filename" Content-Transfer-Encoding: base64 Content-Disposition: attachment $attachment --PHP-mixed-$random_hash-- "; $message = ob_get_clean(); $fh=fopen('log.txt','w'); fwrite($fh,$message); $mail_sent = @mail( $to, $subject, $message, $headers ); return $mail_sent ? "Mail sent" : "Mail failed"; }
除非你这样做才能了解MIME邮件的内部运作,否则标准答案是使用像PHPMailer或Swiftmailer这样的邮件程序库,它可以处理开箱即用的附件。
SwiftMailer关于如何附加文件的例子在这里。
链接地址: http://www.djcxy.com/p/59629.html上一篇: mail with attachment