【问题标题】:Php attachment from string来自字符串的 PHP 附件
【发布时间】:2015-01-24 20:22:08
【问题描述】:

我有一个生成 .pdf 文件的脚本。该脚本将此文件作为字符串返回,然后我可以使用 file_put_contents() 保存它

$output = $dompdf->output();
file_put_contents("myfile.pdf", $output);

我想使用 PHPMailer 将此文件作为附件添加到我的电子邮件中。如果我在磁盘上有一个文件,我只需写入它的路径和新名称:

$mail->addAttachment('/path/to/file.pdf', 'newname.pdf'); 

但是我可以在不将 myfile.pdf 保存到磁盘的情况下添加附件吗?类似的东西:

$mail->addAttachment($output, 'myfile.pdf'); 

此字符串返回错误:

PHP Fatal error:  Call to a member function addAttachment() on a non-object

如何在不保存的情况下将字符串类型转换为文件类型?

更新: 完整代码

$output = $dompdf->output();
$name = 'title.pdf';
    $mail->isSMTP();                                      // Set mailer to use SMTP
$mail->SMTPDebug = 2;
$mail->Host = 'smtp.***.org';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '***@***.orgg';                 // SMTP username
$mail->Password = '******************';                           // SMTP password
$mail->SMTPSecure = 'tls';

$mail->From = 'aaa@bbb.com';
$mail->FromName = 'John';
$mail->addAddress('peter@parker.com', 'Joe User');     // Add a recipient

$mail->addStringAttachment($output, $name);

                          // Set email format to HTML

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

【问题讨论】:

    标签: php email attachment phpmailer email-attachments


    【解决方案1】:

    有一个addStringAttachment() 方法似乎适合您的需要:

    addStringAttachment()

    addStringAttachment(string $string, string $filename, string $encoding = self::ENCODING_BASE64, string $type = '', string $disposition = 'attachment') : boolean

    添加字符串或二进制附件(非文件系统)。

    此方法可用于附加 ascii 或二进制数据,例如数据库中的 BLOB 记录。

    【讨论】:

      【解决方案2】:

      您不能将文件保存到临时目录然后从那里附加吗?并添加一些代码,一旦PHPMailer-&gt;send() 返回 TRUE,您将删除临时文件。

      查看 PHPMailer 类并查看它对 addAttachment 方法所做的检查。

      此外,错误实际上看起来像您的 PHPMailer 对象未启动。请您发布您的整个 PHPMailer 代码块。

      【讨论】:

        【解决方案3】:

        这很简单:只需调用addStringAttachment 而不是addAttachment

        $mail->addStringAttachment($dompdf->output(), 'my.pdf');
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-04-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-04
          • 1970-01-01
          相关资源
          最近更新 更多