Php attachment from string

故事扮演 提交于 2019-12-11 13:26:43

问题


I have a script generating .pdf file. This script return this file as string and then I can save it with file_put_contents()

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

I want to add this file as attachment to my email using PHPMailer. If I have a file on disk I just write path to it and new name:

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

But can I add attachment without saving myfile.pdf to disk? Something like that:

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

This string returns an error:

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

How can I transform string type to file type without saving?

UPD: Full code

$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';
}

回答1:


There's an addStringAttachment() method that seems to fit your need:

addStringAttachment()

addStringAttachment(string $string, string $filename, string 
$encoding, string $type, string $disposition) : void

Add a string or binary attachment (non-filesystem).

This method can be used to attach ascii or binary data, such as a BLOB record from a database.




回答2:


Can't you just save the file to a temporary directory and then attach it from there? And add some code that once PHPMailer->send() returns TRUE that you delete the temporary file.

Look into the PHPMailer class and see what check it makes on the addAttachment method.

Also the error actually looks like your PHPMailer object is not initiated. Can you post your whole PHPMailer code block please.




回答3:


This is very simple: just call addStringAttachment instead of addAttachment:

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


来源:https://stackoverflow.com/questions/28129848/php-attachment-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!