PHP - 发送带有附件的电子邮件不显示消息内容 [英] PHP - sending email with attachment does not show message content

查看:189
本文介绍了PHP - 发送带有附件的电子邮件不显示消息内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试创建一个脚本,我可以发送带有附件的电子邮件。一切都很好,除了当我不在电子邮件中添加文件,我仍然可以看到一个附件与0B,没有名称。

Trying to create a script where I can send an email with attachments. Everything works well except that when I don't add a file in the email I can still see an attachment with 0B and no name.

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>";

}

我做错了什么?任何建议?

what am I doing wrong? Any advice?

推荐答案

当没有附件时,请排除此问题:

Just exclude this when there is no attachment:

--_1_$boundary
Content-Type: application/octet-stream; name=\"$filename\" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

$attachment
--_1_$boundary--

例如,只将其附加到 $ message 当文件名不为空时:

For example, only appending it to $message when the filename is not empty:

$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";

if (!empty($filename))
{
   $message .= " --_1_$boundary
        Content-Type: application/octet-stream; name=\"$filename\" 
        Content-Transfer-Encoding: base64 
        Content-Disposition: attachment 

        $attachment
        --_1_$boundary--";
}

这篇关于PHP - 发送带有附件的电子邮件不显示消息内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆