使用php发送带附件的电子邮件

时间:2011-05-30 10:41:01

标签: php email

我有这个代码 - 邮件附件..........但我收到错误

<?php
    $name = "Reviewbox";
    $email = "jmaster@gmail.com";
    $to = "$name <$email>";
    $from = "Reviewbox ";
    $subject = "Here is your attachment";
    $fileatt = "doc.pdf";
    $fileatttype = "application/pdf";
    $fileattname = "newname.pdf";
    $headers = "From: $from";
    $file = fopen($fileatt, 'rb');
    $data = fread($file, filesize($fileatt));
    fclose($file);
    $semi_rand = md5(time());
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

    $headers .= "\nMIME-Version: 1.0\n" .
    "Content-Type: multipart/mixed;\n" .
    " boundary=\"{$mime_boundary}\"";

    $message = "This is a multi-part message in MIME format.\n\n" .
    "-{$mime_boundary}\n" .
    "Content-Type: text/plain; charset=\"iso-8859-1\n" .
    "Content-Transfer-Encoding: 7bit\n\n" .

    $message .= "\n\n";

    $data = chunk_split(base64_encode($data));

    $message .= "–{$mime_boundary}\n" .
    "Content-Type: {$fileatttype};\n" .
    " name=\"{$fileattname}\"\n" .
    "Content-Disposition: attachment;\n" .
    " filename=\"{$fileattname}\"\n" .
    "Content-Transfer-Encoding: base64\n\n" .
    $data . "\n\n" .
    "-{$mime_boundary}-\n";

    if(mail($to, $subject, $message, $headers)) {
        echo "The email was sent.";
    }else {echo "There was an error sending the mail.";}
    ?>

但是当我运行这段代码时,我得到一个错误,因为“解析错误:语法错误,意外'@'在C:\ wamp \ www \ working \ mail1.php第3行”.....如何解决这........

2 个答案:

答案 0 :(得分:4)

您使用的是“...”而不是引号"..."。看起来像是从网页复制的代码,它将引号转换为“花哨的引号”并粘贴在文本文件中。

将所有替换为"

答案 1 :(得分:3)

 <?php
    $name = "Reviewbox";
    $email = "jmaster@gmail.com";
    $to = "$name <$email>";
    $from = "Reviewbox ";
    $subject = "Here is your attachment";
    $fileatt = "doc.pdf";
    $fileatttype = "application/pdf";
    $fileattname = "newname.pdf";
    $headers = "From: $from";
    $file = fopen($fileatt, 'rb');
    $data = fread($file, filesize($fileatt));
    fclose($file);
    $semi_rand = md5(time());
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

    $headers .= "\nMIME-Version: 1.0\n" .
    "Content-Type: multipart/mixed;\n" .
    " boundary=\"{$mime_boundary}\"";

    $message = "This is a multi-part message in MIME format.\n\n" .
    "-{$mime_boundary}\n" .
    "Content-Type: text/plain; charset=\"iso-8859-1\n" .
    "Content-Transfer-Encoding: 7bit\n\n" .

    $message .= "\n\n";

    $data = chunk_split(base64_encode($data));

    $message .= "–{$mime_boundary}\n" .
    "Content-Type: {$fileatttype};\n" .
    " name=\"{$fileattname}\"\n" .
    "Content-Disposition: attachment;\n" .
    " filename=\"{$fileattname}\"\n" .
    "Content-Transfer-Encoding: base64\n\n" .
    $data . "\n\n" .
    "-{$mime_boundary}-\n";

    if(mail($to, $subject, $message, $headers)) {
        echo "The email was sent.";
    }else {echo "There was an error sending the mail.";}
    ?>