[php]mail函式傳送郵件(正文+附件+中文)
阿新 • • 發佈:2019-01-07
<?php
$from = "[email protected]";
$to = "[email protected], [email protected]";
$subject = "郵件主題";
$subject = "=?UTF-8?B?".base64_encode($subject)."?=";
$attach_filename = date("Y-m-d") . ".html";
$emailBody = "
正文第一行
正文第二行
正文第三行
The end!";
# 然後我們要作為附件的HTML檔案
$attachment = "<html>
<head>
<title>The attached file</title>
</head>
<body>
<h2>This is the attached HTML file</h2>
</body>
</html>";
$boundary = uniqid("");
$headers = "From: $from
To: $to
Content-type: multipart/mixed; boundary=\"$boundary\"";
$emailBody = "--$boundary
Content-type: text/plain; charset=utf-8
Content-transfer-encoding: 8bit
$emailBody
--$boundary
Content-type: text/html; name=$attach_filename
Content-disposition: inline; filename=$attach_filename
Content-transfer-encoding: 8bit
$attachment
--$boundary--";
mail(" [email protected]", $subject, $emailBody, $headers);
?>
按照上例是能傳送成功, 但專案中真正使用時, 卻出現了亂碼的問題:
當正文或附件html一行很長的時候, 收到的內容有亂碼和!等異常, 查閱到有人說html郵件一行不能超過80個字元,抱著試一試的態度,
生成html附件內容字串的時候用類似 $html .= "<tr>"; $html .= "<td>xxx</td>\n"; $html .= "<td>xxxx</td>\n"; $html .= "</tr>"; 的方法, html每增加一點內容,加上 \n.既保證郵件body單行不超過80字元,有保證<tr> </tr> <td> </td>不會被wordwrap折斷.
經過這麼一折騰, 完美解決了亂碼.
啊哈...