如何使用PHP邮件功能将PDF附加到电子邮件

时间:2012-05-15 18:19:28

标签: email email-attachments php

我正在使用PHP邮件功能发送电子邮件,但我想将指定的PDF文件添加为电子邮件的文件附件。我该怎么做?

这是我目前的代码:

$to = "me@myemail.com";
$subject = "My message subject";
$message = "Hello,\n\nThis is sending a text only email, but I would like to add a PDF attachment if possible.";
$from = "Jane Doe <janedoe@myemail.com>";

$headers = "From:" . $from; 
mail($to,$subject,$message,$headers);

echo "Mail Sent!";

3 个答案:

答案 0 :(得分:20)

您应该考虑使用诸如PHPMailer之类的PHP邮件库,这样可以使邮件发送的过程更简单,更好。

以下是如何使用PHPMailer的示例,它非常简单!

<?php

require_once('../class.phpmailer.php');

$mail             = new PHPMailer(); // defaults to using php "mail()"

$body             = file_get_contents('contents.html');
$body             = eregi_replace("[\]",'',$body);

$mail->AddReplyTo("name@yourdomain.com","First Last");

$mail->SetFrom('name@yourdomain.com', 'First Last');

$mail->AddReplyTo("name@yourdomain.com","First Last");

$address = "whoto@otherdomain.com";
$mail->AddAddress($address, "John Doe");

$mail->Subject    = "PHPMailer Test Subject via mail(), basic";

$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

$mail->MsgHTML($body);

$mail->AddAttachment("images/phpmailer.gif");      // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}

?>

PHPMailer的替代方法是http://swiftmailer.org/

答案 1 :(得分:2)

简单回答:不要这样做。手动构建MIME电子邮件是一件痛苦的事情,非常容易搞砸。

相反,请使用PHPMailerSwiftmailer。用它们做附件几乎是微不足道的,如果出现爆炸的话,你可以获得更好的反馈,v。 mail()屈服于吐出的简单真/假。

答案 2 :(得分:1)

消除弃用错误,

替换

$body             = eregi_replace("[\]",'',$body);

$body             = preg_replace('/\.([^\.]*$)/i','',$body);