14

我正在使用 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!";
4

3 回答 3

20

您应该考虑使用 PHP 邮件库,例如PHPMailer,这将使发送邮件的过程更加简单和更好。

下面是一个如何使用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/

于 2012-05-15T18:23:46.100 回答
3

简单的回答:不要这样做。手动构建 MIME 电子邮件是一项痛苦的工作,而且很容易搞砸。

相反,使用PHPMailerSwiftmailer。用它们做附件几乎是微不足道的,而且你会得到 FAR FAR FAR 更好的反馈,以防万一发生了什么事情,而不是 mail() 屈尊吐出的简单真/假。

于 2012-05-15T18:22:50.050 回答
1

为了消除弃用错误,

代替

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

$body             = preg_replace('/\.([^\.]*$)/i','',$body);
于 2016-02-24T18:55:02.870 回答