如何使用 PHP 邮件功能将 PDF 附加到电子邮件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10606558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to attach PDF to email using PHP mail function
提问by JROB
I am sending an email using PHP mail function, but I would like to add a specified PDF file as a file attachment to the email. How would I do that?
我正在使用 PHP 邮件功能发送电子邮件,但我想将指定的 PDF 文件作为文件附件添加到电子邮件中。我该怎么做?
Here is my current code:
这是我当前的代码:
$to = "[email protected]";
$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 <[email protected]>";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent!";
回答by josmith
You should consider using a PHP mail library such as PHPMailerwhich would make the procedure to send mail much simpler and better.
您应该考虑使用 PHP 邮件库,例如PHPMailer,这将使发送邮件的过程更加简单和更好。
Here's an example of how to use PHPMailer, it's really simple!
这里有一个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("[email protected]","First Last");
$mail->SetFrom('[email protected]', 'First Last');
$mail->AddReplyTo("[email protected]","First Last");
$address = "[email protected]";
$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!";
}
?>
An alternative to PHPMailer is http://swiftmailer.org/
PHPMailer 的替代方法是http://swiftmailer.org/
回答by Marc B
Simple answer: Don't do it. building a MIME email by hand is a painful business, and VERY easy to screw up.
简单的回答:不要这样做。手动构建 MIME 电子邮件是一项痛苦的工作,而且很容易搞砸。
Instead, use PHPMaileror Swiftmailer. It's almost trivial to do attachments with them, and you get FAR FAR FAR better feedback in case something does blow up, v.s. the simple true/false that mail() condescends to spit out.
相反,请使用PHPMailer或Swiftmailer。用它们做附件几乎是微不足道的,你会得到更好的反馈,以防万一发生问题,而不是 mail() 屈尊吐出的简单的真/假。
回答by sspence65
To eliminate deprecation errors,
为了消除弃用错误,
Replace
代替
$body = eregi_replace("[\]",'',$body);
With
和
$body = preg_replace('/\.([^\.]*$)/i','',$body);

