Search code examples
phpphpmailer

str_ireplace for file_put_content not working


I tried replacing ##email## with customer email. this works for the body of the email, but doesn't work for attachments.

$attachfile = file_get_contents("attachment/test.txt");
$attachfile = str_ireplace("##email##", $customeremail, $attachfile);
$tempattach = tempnam("/tmp", 'prefix');
file_put_contents($tempattach.".txt", $attachfile);
$mail->addAttachment($tempattach.".txt", "Hello.txt"]), "base64");
unlink($tempattach.".txt");

Solution

  • Attachments are not actually read until you send. So if you add an attachment file and delete it before sending (which is what you're doing), it will not be sent.

    From what you're doing though, it looks like you might be better off skipping the external files and doing that substitution and attachment all in memory using addStringAttachment like this:

    $attachfile = file_get_contents("attachment/test.txt");
    $attachfile = str_ireplace("##email##", $customeremail, $attachfile);
    $mail->addStringAttachment($attachfile, "Hello.txt");