来自字符串的Php附件

问题描述 投票:1回答:3

我有一个生成.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

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

UPD:完整代码

$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 = '[email protected]';
$mail->FromName = 'John';
$mail->addAddress('[email protected]', '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
3个回答
2
投票

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

addStringAttachment()

addStringAttachment()

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

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


1
投票

难道不能只将文件保存到一个临时目录,然后从那里附加它?并添加一些代码,一旦addStringAttachment(string $string, string $filename, string $encoding = self::ENCODING_BASE64, string $type = '', string $disposition = 'attachment') : boolean返回TRUE,便删除了临时文件。

查看PHPMailer类,查看它对addAttachment方法进行的检查。

而且该错误实际上看起来还没有启动您的PHPMailer对象。您能否发布整个PHPMailer代码块。


1
投票

这很简单:只需调用PHPMailer->send()而不是addStringAttachment

addAttachment
© www.soinside.com 2019 - 2024. All rights reserved.