php 带有 pdf 附件和 html 消息的邮件功能

php mail function with pdf attachment and html message

我在发送带有 PDF 附件的电子邮件时遇到问题,邮件内容是 html 格式。请检查我下面的代码。 HTML 电子邮件工作正常。但问题出在pdf附件中。

<?php
$random_hash = md5(date('r', time()));
$headers = "From: ".$from."\r\nReply-To: ".$from;
$headers .= "\r\nContent-Type: text/html; boundary=\"PHP-mixed-".$random_hash."\"";

foreach($summaryArray as $summaryArrayValue)
{
  $file  = 'pdf_directory/'.$summaryArrayValue['result_filename'].'.pdf';
  $fileName = $summaryArrayValue['result_filename'];

  $attachment = chunk_split(base64_encode(file_get_contents($file)));
  $message.=<<<EOD
  Content-Type: application/octet-stream; name="{$fileName}" // tried with both application/octet-stream and application/pdf
  Content-Transfer-Encoding: base64
  Content-Disposition: attachment

  {$attachment}
  --PHP-mixed-{$random_hash}--

EOD;
}

$mail_sent = mail( $to, $subject, $message, $headers );
echo $mail_sent ? "Mail sent" : "Mail failed";
?>

使用 PHPMailer 脚本,与使用 PHP 的内置 mail() 函数自己尝试相比,这是一个更容易的选择,而且有很大的优势。 PHP的mail()函数确实不是很好

要使用 PHP邮件程序:

Download the PHPMailer script from here: http://github.com/PHPMailer/PHPMailer
Extract the archive and copy the script's folder to a convenient place in your project.
Include the main script file -- require_once('path/to/file/class.phpmailer.php');

现在,发送带附件的电子邮件从极其困难变得异常简单:

$email = new PHPMailer();
$email->From      = 'you@example.com';
$email->FromName  = 'Your Name';
$email->Subject   = 'Message Subject';
$email->Body      = $bodytext;
$email->AddAddress( 'destinationaddress@example.com' );

$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

return $email->Send();

就那么一行 $email->AddAttachment(); -- 没有比这更简单的了。

如果你用 PHP 的 mail() 函数来做,你将编写一堆代码,而且你可能会有很多很难找到的错误。