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

时间:2015-06-13 11:42:45

标签: 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>";

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

3 个答案:

答案 0 :(得分:1)

如果没有附件,请将其排除:

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

答案 1 :(得分:0)

     $headers = array();
     $headers [] = 'MIME-Version: 1.0';
     $headers [] = 'Content-type: text/html; charset=utf-8';
     $headers [] = 'Reply-To: ' . $From;
     $headers [] = 'X-Mailer: PHP/' . phpversion();
     $headers [] = "Return-Path: " . $From;
     $headers [] = "Errors-To: " . $From;

     $header = implode("\r\n", $headers);
     $fifth = "-f $From";
     if (mail($empfaenger, $betreff, $Mailbody, $header, $fifth)) {};

我认为最后一个标题不应该以'\ r \ n'结尾。此代码是由在手册中发布的人编写的。查看手册,你会在那里找到好的代码。

答案 2 :(得分:0)

如果您想发送带有附件的电子邮件,我建议您使用PHP-Mailer库。它会让你的生活更轻松。

您需要做的就是包含该类并实例化PHPMailer Object

<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
//And you will need to set properties for the object
?>

结帐PHP-Mailer Github Link。他们还给出了一个如何实现

的简单示例