php mail:附件错误

时间:2011-07-05 01:48:45

标签: php email utf-8 attachment send

人!

我必须发送带附件的邮件。 所以我根据互联网上的一些例子得到了一些代码:

$path = $_SERVER['DOCUMENT_ROOT'] . ATTACHMENT_DIR . DS;
$files = array('filename1.ext', 'filename2.ext');
$EOL = "\r\n"; // "\n";

$to = "mail@domain.tld";
$from = '=?UTF-8?B?' . base64_encode($_POST['name']) . '?='  . " <" . $_POST['email'] . ">";
$subject = "subject";
$subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
$message = $_POST['message'];

$mime_boundary = md5(uniqid(time()));

$headers .= "From: $from" .
    "{$EOL}MIME-Version: 1.0{$EOL}" .
        "Content-Type: multipart/mixed; boundary=\"{$mime_boundary}\"{$EOL}{$EOL}" .
        "This is a multi-part message in MIME format.{$EOL}" .
        "-–{$mime_boundary}{$EOL}" .
        "Content-Type: text/plain; charset=UTF-8{$EOL}" .
        "Content-Transfer-Encoding: 8bit{$EOL}{$EOL}" .
        $message . "{$EOL}{$EOL}";

    // preparing attachments
    for ($x = 0; $x < count($files); $x++) {
        $file = fopen($path . $files[$x], "rb");
        $data = fread($file, filesize($path . $files[$x]));
        fclose($file);
        $data = chunk_split(base64_encode($data), 72, $EOL);
        $headers .= "-–{$mime_boundary}{$EOL}" .
            "Content-Type: application/octet-stream; name=\"$files[$x]\"{$EOL}" .
            "Content-Transfer-Encoding: base64{$EOL}{$EOL}" .
            "Content-Disposition: attachment; filename=\"$files[$x]\"{$EOL}" .
            $data . "{$EOL}";
}
$headers .= "--{$mime_boundary}--{$EOL}";

$result = @mail($to, $subject, "", $headers);

它有效,但出了点问题。此代码生成:

To: mail@domain.tld
Subject: =?UTF-8?B?c3ViamVjdA==?=
From: =?UTF-8?B?Sm9obiBEb2U=?= <mail@domail.tld>
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="2dd88e9ef3ae338d9e93bc8448a74093"

This is a multi-part message in MIME format.
-–2dd88e9ef3ae338d9e93bc8448a74093
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

test message

-–2dd88e9ef3ae338d9e93bc8448a74093
Content-Type: application/octet-stream; name="filename1.ext"
Content-Transfer-Encoding: base64

Content-Disposition: attachment; filename="filename1.ext"
R0lGODlhMgAyAPf/ALsoJpcZFeG8wZsoJb+NiKZDQMV6eKgYFqpJR6lWVdKtq6oeHP7//9a0
[cutted]
Qx66WAxbFOMNs8gDJAohCr5Svd8mUEgM7oAI7HghBRMJra6XEhAAOw==

-–2dd88e9ef3ae338d9e93bc8448a74093
Content-Type: application/octet-stream; name="filename2.ext"
Content-Transfer-Encoding: base64

Content-Disposition: attachment; filename="filename2.ext"
R0lGODlhMgAyAPf/ALsoJpcZFeG8wZsoJb+NiKZDQMV6eKgYFqpJR6lWVdKtq6oeHP7//9a0
[cutted]
Qx66WAxbFOMNs8gDJAohCr5Svd8mUEgM7oAI7HghBRMJra6XEhAAOw==

--2dd88e9ef3ae338d9e93bc8448a74093--

收到的消息没有文字或任何附件。请帮我找到合适的解决方案!

2 个答案:

答案 0 :(得分:1)

我责怪base64_encode。

尝试使用http://www.zedwood.com/article/126/php-mail-function-with-attachments处的代码,看看它是否更有效。

答案 1 :(得分:0)

您没有使用Mail_Mime的任何特殊原因?