I'm trying to send an .html file as an attachment using PHP-mailer, however, I want to dynamically modify some values in the file before it's added and sent. I'm not sure if my logic is okay but the email is sending but it's not sending with an attachment. Below is my code sample.
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()
arguments seem to be wrong. First argmument is file name, and I don't think you want $attStr
to be the filename. Also it returns the number of bytes written or false and sets $templateFile
to it.
Here is a rewrite with a cleaner approach:
$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');