【发布时间】:2015-08-29 08:39:09
【问题描述】:
尝试创建一个脚本,我可以在其中发送带有附件的电子邮件。一切正常,除了当我不在电子邮件中添加文件时,我仍然可以看到一个 0B 且没有名称的附件。
if(isset($_POST["my_send"])){
$email_to = $_POST['my_email_to']; //required
$email_from = "myemail@example.co.uk"; // required
$subject = $_POST['my_subject']; // not required
$comments = $_POST['write_my_email']; // required
$email_message .= stripcslashes("$comments");
$attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name'])));
$filename = $_FILES['file']['name'];
// create email headers
$headers = 'From: '.$email_from."\r\n".
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"_1_$boundary\"\r\n";
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
$message="This is a multi-part message in MIME format.
--_1_$boundary
Content-Type: multipart/alternative; boundary=\"_2_$boundary\"
--_2_$boundary
Content-Type: text/plain; charset=\"iso-8859-1\"
Content-Transfer-Encoding: 7bit
$email_message
--_2_$boundary--
--_1_$boundary
Content-Type: application/octet-stream; name=\"$filename\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--_1_$boundary--";
mail($email_to, $subject, $message, $headers);
echo "<h5>Thanks, your email was sent successfully!</h5>";
}
我做错了什么?有什么建议吗?
【问题讨论】:
-
在没有附件时更改标题类型
-
顺便说一句,如果你想包含带双引号的多行字符串,为什么不使用
heredoc?它使写入和读取字符串变得更加容易。
标签: php email email-attachments