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

JRO*_*ROB 13 php email email-attachments

我正在使用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!";
Run Code Online (Sandbox Code Playgroud)

jos*_*ith 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!";
}

?>
Run Code Online (Sandbox Code Playgroud)

PHPMailer的替代品是http://swiftmailer.org/

  • 你还没有回答这个问题.您只是提出了一个非常好的解决方案.用户需要PHP邮件功能才能发送pdf. (5认同)