在PHP中,如何发送带附件的HTML电子邮件?

时间:2011-07-14 13:18:27

标签: php html email content-type mime

我有一个发送给自己的表单,允许人们附加文件。但我似乎无法在邮件中允许HTML。我想我需要两种不同的内容类型:

        $to     = "my@email.com"; // Webmaster
        $subj   = "Great Subject";
        $message = strip_tags($_POST['message']);
        $attachment = chunk_split(base64_encode(file_get_contents($_FILES['attachment']['tmp_name'])));
        $filename = $_FILES['attachment']['name'];
        $boundary =md5(date('r', time())); 
        $headers = "From: $fname $lname <$email>\r\nReply-To: $fname $lname <$email>";
        $headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";
        $message .= "Here is your <strong>File</strong>.".\r\n" ;
        $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

$message

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

$attachment
--_1_$boundary--";

        mail($to, $subj, $message, $headers);

1 个答案:

答案 0 :(得分:6)

使用PHPMailer等类,因为它会使其更简单。