0

I am using the ExtendedMailMessage class to try and send an email with an attachments to my clients. The issue is I am sending the email inside a foreach loop and for some reason even though I am defining a new attachment the new attachment is just being appended to an array and each client gets multiple attachments instead of one.

$extendedMailer = $this->ci->extendedMailer;

foreach ($emails as $email) {
    $attachment = new MailAttachment(
        base64_decode($base64String), "report.pdf"
    );

    try {
        $message = new ExtendedTwigMailMessage($this->ci->view, 'mail/pdf-reports.html.twig');

        $message->from($config['address_book.admin'])
            ->addEmailRecipient(new EmailRecipient($email, 'Client'))
            ->setFromEmail($config['address_book.admin'])
            ->setReplyEmail($config['address_book.admin'])
            ->addAttachment($attachment);

        $extendedMailer->sendDistinct($message);
    }
    catch(\Exception $ex) {
        var_dump($email);
    }
}

The first client will receive 1 attachment and then the 2nd will receive 2 attachments, 3rd will receive 3 attachments etc...

How do I just send 1 attachement with each email instead of appending it to the old attachments

Vishal Vasani
  • 647
  • 8
  • 16
Lukerayner
  • 412
  • 6
  • 23
  • Since `addAttachment` is not part of UserFrosting code, it would be necessary to see you implemented it in `ExtendedTwigMailMessage`. – Louis Charette May 29 '22 at 23:34

1 Answers1

0

Since PHPMailer instance is reused for each email, anything set on PHPMailer is carried on to the next email. When the Mailer's send or sendDistinct methods are called, only the recipients are explicitly cleared. So in your case, you might need to explicitly clear the attachement from $message between each email (depending how your addAttachment is implemented).

Another solution might be to move the addAttachment call outside the loop, assuming each email as the same attachement :

$extendedMailer = $this->ci->extendedMailer;

$attachment = new MailAttachment(
    base64_decode($base64String), "report.pdf"
);

$message = new ExtendedTwigMailMessage($this->ci->view, 'mail/pdf-reports.html.twig');
$message->from($config['address_book.admin'])
        ->setFromEmail($config['address_book.admin'])
        ->setReplyEmail($config['address_book.admin'])
        ->addAttachment($attachment);

foreach ($emails as $email) {
   
    try {
        $message->addEmailRecipient(new EmailRecipient($email, 'Client'));
        $extendedMailer->sendDistinct($message);
    }
    catch(\Exception $ex) {
        var_dump($email);
    }
}

Note that the following fix will be introduced in UserFrosting V5 send/sendDistinct to avoid this issue :

// Clone phpMailer so we don't have to reset it after sending.
$phpMailer = clone $this->phpMailer;
Louis Charette
  • 1,325
  • 1
  • 10
  • 34