我试图使用PHP mailer发送一个.html文件作为附件,但是,我想在添加和发送文件之前动态修改文件中的一些值。我不确定我的逻辑是否正确,但电子邮件正在发送,但没有附带附件。下面是我的代码示例。
for($i=0; $i<count($_FILES['attachment']['name']); $i++) {
if ($_FILES['attachment']['tmp_name'][$i] != ""){
$templateFile = $_FILES['attachment']['tmp_name'];
$attStr = file_get_contents($templateFile);
$attStrNew = str_replace("[-email-]" ,$email, $attStr );
$templateFile = file_put_contents($attStr, $attStrNew);
$mail->AddAttachment($templateFile[$i],$_FILES['attachment']['name'][$i]);
}
}
file_put_contents()
参数似乎是错误的。第一个参数是文件名,我认为您不希望$attStr
作为文件名。它还返回写入的字节数或false,并将$templateFile
设置为它
这里有一个更干净的重写方法:
- 为tmp文件创建一个数组
- 浏览所有附件
- 读取模板文件
- 替换模板变量
- 将新内容写入新的tmp文件
- 收集发送后要删除的tmp文件名
- 将tmp文件设置为附件
$tmpFiles = [];
foreach ($_FILES['attachment']['name'] as $filename) {
if (empty($filename)) {
continue;
}
$content = file_get_contents($filename);
$content = str_replace("[-email-]", $email, $content);
$tmpFilename = tempnam("/tmp", 'attachment');
$tmpFiles[] = $tmpFilename;
file_put_contents($tmpFilename, $content);
$mail->AddAttachment($tmpFilename, $filename);
}
// send the mail and then delete the tmp files.
array_walk($tmpFiles, 'unlink');