发送带有PHP问题的电子邮件pdf附件

时间:2011-11-17 19:18:53

标签: php html email

我正在尝试制作一个脚本,以便稍后发送电子邮件并附加pdf或其他类型的文件。

我一直在关注各种教程并走到了尽头。

有人能看到我的代码有什么问题吗?我想我已经看了太久了。

<?php
    include ("../../includes/auth.php");

    $id = $_GET['id'];
    $date = date('y-m-d h:i:s');

    $recipient = $_GET['email'];
    $lname = $_GET['lname'];
    $fname = $_GET['fname'];
    $subject ="Enquiry Form - $date";
    //-------------attachment stuff----------
    $fileatt = "/test.pdf";
    $fileatttype = "application/pdf";
    //$fileattname = "newname.pdf";
    $file = fopen($fileatt, 'rb');
    $data = fread($file, filesize($fileatt));
    fclose($file);
    $semi_rand = md5(time());
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
    //-------------------------------------
    $headers = "From: test person <info@test.co.uk>";
    $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=\"{$fileatt}\"\n" .
    "Content-Transfer-Encoding: base64\n\n" .
    $data . "\n\n" ."--{$mime_boundary}--\n";
    $message ."Dear ".$fname." ".$lname." Test message".$date;

    echo $recipient."<br />";
    echo $subject."<br />";
    echo $message."<br />";
    echo $headers."<br />";

    mail($recipient, $subject, $message, $headers);

    include ("../../includes/dbconn.php");

    $set_datesent = "UPDATE _leads SET `Covering_letter_sent` = '$date' WHERE `ID` = '$id'";
    //echo $set_datesent;
    $result = mysql_query ($set_datesent, $connection)
    or die ("Failed to perform query :  $sql <br />".mysql_error());
?>

3 个答案:

答案 0 :(得分:1)

我建议您使用类似PEAR Mail库的内容。然后发送附件变得像下面的代码一样简单易读。您必须确保安装了邮件库,但这是一项相当简单的任务。

require_once('Mail.php');
require_once('Mail/mime.php');

$text = wordwrap($message, 70); // You'd put the text version of your message here as $message

$mime = new Mail_Mime();
$mime->setTXTBody($text);
$mime->setFrom($name . ' <' . $from_email . '>'); // The sender name and email ID go here
$mime->addAttachment($fpath, $ftype); // File path and type go here
$mime->setSubject($subject); // Subject goes here

$body = $mime->get()
$headers = $mime->headers();

$mail =& Mail::factory('mail');
$mail->send($to_email, $headers, $body); // The recipients email address goes here

unset($mime, $mail);

通过这种方式,其他事情也变得更加容易,例如,编写HTML邮件。

答案 1 :(得分:0)

我强烈建议使用像SwiftMailer这样的库。它是免费的,简化了你的生活。

答案 2 :(得分:0)

我建议使用Pear Mail_mime包(http://pear.php.net/package/Mail_Mime/)。我曾经手工处理过附件,因为我不知道这样的库存在(愚蠢的我),当我想出来的时候,我立即摆脱了我制作糟糕的脚本并开始使用Mail_mime。它没有什么小故障,但是,它比手动编码要容易得多。