How to send multiple emails?

199 Views Asked by At

I'm trying to send email to selected users by nette mailer but it allways results with an InvalidStateException.

public function contactsEditorFormSucceeded($form, $values)
{
        try {
            $recipients = $values->recipients;
            $mail = new Message;                      
            $mail->setFrom($values->email)
                ->setSubject($values->subject)
                ->setBody($values->message);
                foreach ($recipients as $recipient) {
                    $mail->addTo($recipient);
                }
    $mailer = new SendmailMailer;
        $mailer->send($mail);
    $this->flashMessage('Done.', self::MSG_SUCCESS);
        $this->redirect('this');
        } catch (InvalidStateException $ex) {
        $this->flashMessage('Error', self::MSG_ERROR);
        }
}    

I'm using foreach to get multiple addTo() but it will not send the mails.

1

There are 1 best solutions below

1
On

Message can not have multiple recipients. It is necessary to create a cycle and create so many messages about how many recipients are

public function contactsEditorFormSucceeded($form, $values)
{
    try {
        $recipients = $values->recipients;

        foreach ($recipients as $recipient) {
            $mail = new Message;                      

            $mail->setFrom($values->email)
                ->setSubject($values->subject)
                ->setBody($values->message)
                ->addTo($recipient);

            $mailer = new SendmailMailer;
            $mailer->send($mail);
        }

        $this->flashMessage('Done.', self::MSG_SUCCESS);
        $this->redirect('this');

    } catch (InvalidStateException $ex) {
        $this->flashMessage('Error', self::MSG_ERROR);
    }
}