【问题标题】:php mail function with pdf attachment and html message带有pdf附件和html消息的php邮件功能
【发布时间】:2015-12-10 02:34:24
【问题描述】:

我在发送带有 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";
?>

【问题讨论】:

    标签: php email pdf sendmail email-attachments


    【解决方案1】:

    使用 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() 函数来做这件事,你会写一堆代码,而且你可能会有很多很难找到的错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-25
      • 1970-01-01
      • 2015-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-16
      • 2017-03-16
      相关资源
      最近更新 更多