【问题标题】:How to attach PDF to email using PHP mail function如何使用 PHP 邮件功能将 PDF 附加到电子邮件
【发布时间】:2012-05-23 07:24: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!";

【问题讨论】:

标签: email email-attachments php


【解决方案1】:

您应该考虑使用 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/

【讨论】:

  • 如果我的附件存储在远程服务器上怎么办?有什么变化还是应该起作用?
  • AddAttachment() 不支持远程文件:Add an attachment from a path on the filesystem 提前使用file_get_contents(),@paulalexandru ...? ://
  • 您还没有回答问题。您只是提出了一个替代解决方案。用户需要 PHP 邮件功能来发送 pdf。
  • + @Nebula 我不知道这是怎么被接受的答案。
【解决方案2】:

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

改为使用PHPMailerSwiftmailer。用它们做附件几乎是微不足道的,而且你会得到 FAR FAR FAR 更好的反馈,以防万一发生爆炸,v.s. mail() 屈尊吐出的简单真/假。

【讨论】:

    【解决方案3】:

    为了消除弃用错误,

    替换

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 2010-12-07
      • 2012-12-14
      • 2020-11-21
      • 2013-03-17
      • 1970-01-01
      相关资源
      最近更新 更多