PHPMailer附件,在没有物理文件的情况下执行此操作

2022-08-30 16:31:43

所以:

// Setup mail class, recipients and body
$mailer->AddAttachment('/home/mywebsite/public_html/file.zip', 'file.zip');
The AddAttachment function has four arguments:

AddAttachment(PATH_TO_FILE, FILENAME, ENCODING, HEADER_TYPE)

我曾经使用xmail(),当我在这里添加附件时,我传递了文件名和内容,应该在其中。

喜欢这个:

$xmail->addAttachment('myamazingfile.pdf', $content);

我怎样才能使它以相同的方式工作,所以当我从PHPmailer类调用时,我可以传递相同或类似的东西,所以我不需要在我的服务器上有一个实际的文件来发送?AddAttachment()


答案 1
AddStringAttachment($string,$filename,$encoding,$type)

例如

$mail = new PHPMailer();
$mail->AddStringAttachment($string,$filename,$encoding,$type);

https://phpmailer.github.io/PHPMailer/classes/PHPMailer-PHPMailer-PHPMailer.html#method_addStringAttachment


答案 2

由于 AddAttachment() 函数需要路径而不是字节数据,因此您应该执行 php 转换为 temp 文件函数,然后将该路径字符串传递到函数中

$prefix     = 'ConvertMediaArgs_'.time().'_';
$tempfile   = tempnam( $this->tempdir, $prefix );

// Args file create failure: kill script with TEMPFILEFAIL error
if($tempfile === false) {
    die('file could not be created');
}

// Write args as Key=Val (\n) to file
$fullpath   = $this->tempdir.$tempfile;
$content    = $someContent // <---------------- this is your file's data
$handle     = fopen( $tempfile, "w");
fwrite( $handle, $content );

// $fullpath is the path you wanna pass to your function
$xmail->addAttachment( $fullpath, $content );

推荐