繁体   English   中英

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

[英]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()函数确实不是很好。

要使用PHPMailer:

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()函数来执行此操作,则将编写代码堆栈,并且可能会发现很多非常困难的bug。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM