PHP - 发送带附件的电子邮件不显示邮件内容

标签 php email email-attachments

尝试创建一个脚本,我可以在其中发送带附件的电子邮件。一切正常,除了当我不在电子邮件中添加文件时,我仍然可以看到带有 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>";

}

我做错了什么?有什么建议吗?

最佳答案

没有附件就排除这个:

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

$attachment
--_1_$boundary--

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

$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 - 发送带附件的电子邮件不显示邮件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30818263/

相关文章:

java - Android - 无法使用 FileProvider 添加电子邮件附件

使用 p7s 数字签名的 Android Intent 来签署电子邮件

php - 为此我需要某种缓存机制吗?

php - 发送带有内嵌图像的电子邮件

php - MySQL插入和更新优化

PHPMailer : MAIL not accepted from server: 530 5. 7.0 必须先发出 STARTTLS 命令

php - 如何使用 PHP 中数据库中的内容将 HTML 文件附加到电子邮件?

php - php mysql 用括号分割一个变量

ruby-on-rails - Rails - 电子邮件链接验证和电话号码验证以及 URL 验证

java - 如何使用 java mail api 发送任何类型的附件?