PHP发送带有附件的电子邮件
我似乎找不到我编写的应该发送带有附件的电子邮件的php函数的问题。我已经为此苦苦挣扎了一段时间了。
function myMail($to, $subject, $mail_msg, $filename, $contentType){ $random_hash = md5(date('r', time()));
$headers = "From: webmaster@example.com\r\nReply-To: ".$to;
$headers .= "\r\nContent-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";
}
问题是邮件的消息与文件混合在一起并作为附件发送。
回答:
Artefacto让我更加关注输出,并且找到了解决方法:
函数myMail($ to,$ subject,$ mail_msg,$ filename,$ contentType,$ pathToFilename){ $ random_hash = md5(date('r',time()));
$ headers =“发件人:webmaster@mysite.com \ r \ n回复至:”。$ to;
$ headers。=“” \ r \ nContent-Type:multipart / mixed; boundary = \“ PHP-mixed-”。$ random_hash。“ \”“;
$ attachment = chunk_split(base64_encode(file_get_contents($ pathToFilename)));;
ob_start();
回声“
--PHP-mixed- $ random_hash
内容类型:多部分/替代;boundary = \“ PHP-alt- $ random_hash \”
--PHP-alt- $ random_hash
内容类型:文本/纯文本;charset = \“ utf-8 \”
内容传输编码:7bit
$ mail_msg
--PHP-alt- $ random_hash--
--PHP-mixed- $ random_hash
内容类型:$ contentType; 名称= \“ $文件名\”
内容传输编码:base64
内容处置:附件
$附件
--PHP-mixed- $ random_hash--
“;
$ message = ob_get_clean();
$ fh = fopen('log.txt','w');
fwrite($ fh,$ message);
$ mail_sent = @mail($ to,$ subject,$ message,$ headers);
返回$ mail_sent吗?“邮件已发送”:“邮件失败”;
}
以上是 PHP发送带有附件的电子邮件 的全部内容, 来源链接: utcz.com/qa/411207.html