小编典典

使用PHP Mail()发送附件?

php

我需要通过邮件发送pdf文件,可以吗?

$to = "xxx";
$subject = "Subject" ;
$message = 'Example message with <b>html</b>';
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: xxx <xxx>' . "\r\n";
mail($to,$subject,$message,$headers);

我想念什么?


阅读 382

收藏
2020-05-26

共1个答案

小编典典

我在评论中同意@MihaiIorga–使用PHPMailer脚本。听起来您正在拒绝它,因为您想要更简单的选择。相信我,与尝试使用PHP的内置函数自己相比,PHPMailer 在很大程度上 更容易的选择mail()。PHP的mail()功能确实不是很好。

要使用PHPMailer:

  • 从此处下载PHPMailer脚本
  • 提取档案并将脚本的文件夹复制到项目中的方便位置。
  • 包括主脚本文件- require_once('path/to/file/class.phpmailer.php');

现在,发送带有附件的电子邮件已经从疯狂的困难变成了难以置信的轻松:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$email = new PHPMailer();
$email->SetFrom('you@example.com', 'Your Name'); //Name is optional
$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。

2020-05-26