使用phpmailer发送带有动态附件(pdf)的邮件会返回pdf格式的错误



我使用php mailer附加并发送发票pdf。

这是我用来发送邮件的

$string = file_get_contents("http://website.com/page/pdf_vouch.php&pvno=$pv&mnth=$mnth&yr=$yr&email=$email&final=$final&name=$ms_n"); 
$mail->AddStringAttachment($string, "sales_invoice.pdf", $encoding = 'base64', $type = 'application/pdf');

通过这个,我将一些值发送到一个特定的页面,该页面将生成pdf,并将通过电子邮件发送生成的pdf作为附件。

问题出在name参数上。当我只将名称作为字符串时,将发送带有附件的邮件,并可以打开pdf。但如果它是一个变量,那么邮件会被发送,但pdf不会打开,并显示一些错误,比如它没有正确解码。

我正在从数据库中获取名称变量。

有人能告诉我可能的问题是什么吗。

您需要对嵌入URL中的任何参数进行URL编码:

$string = file_get_contents(
    "http://website.com/page/pdf_vouch.php&pvno=".rawurlencode($pv).
    "&mnth=".rawurlencode($mnth).
    "&yr‌​=‌".rawurlencode(​$yr).
    "&email=".rawurlencode($email).
    "&final=".rawurlencode($final).
    "&name=".rawurlencode($ms_n)
);

urlencode()生成Javascript风格的编码,使用+对空间进行编码,在向用户显示URL的情况下,这种编码的可读性稍高,但当一切都发生在后端时,这就不成问题了,就像本例中一样。对于更健壮的编码,请使用rawurlencode(),它将空间编码为%20

当您的变量可能包含URL中有意义的字符时,正确的编码尤为重要,我怀疑这就是您遇到的问题——例如,如果$final包含&name=foo,如果不编码,则会导致与真正的name参数混淆。

如果您已经验证了其中的一些(例如,如果您已经知道$yr只包含数字),则可以跳过其中的一些。

如果您提供了嵌入URL中的变量的示例值,这个问题会更快地得到回答。

使用$mail->addAttachment而不是$mail->addStringAttachment

由于PHPMailer不会自动获取远程内容,您需要自己完成。

所以你去:

// we can use file_get_contents to fetch binary data from a remote location
$url = 'http://website.com/page/pdf_vouch.php&pvno=$pv&mnth=$mnth&yr=$yr&email=$email&final=$final&name=$ms_n';
$binary_content = file_get_contents($url);
// You should perform a check to see if the content
// was actually fetched. Use the === (strict) operator to
// check $binary_content for false.
if ($binary_content) {
   throw new Exception("Could not fetch remote content from: '$url'");
}
// $mail must have been created
$mail->AddStringAttachment($binary_content, "sales_invoice.pdf", $encoding = 'base64', $type = 'application/pdf');
// continue building your mail object...

最新更新