3

In my plugin, I'm sending an email like this:

$recipients = '[email protected]';

$email = new EmailModel();
$email->toEmail = $recipients;
$email->subject = 'My Email Subject';
$email->body    = 'My Email Body';

craft()->email->sendEmail($email);

Which works great! But when I'm sending to multiple people, the string would look like this...

$recipients = '[email protected], [email protected]';

... and it generates an error:

Invalid address: [email protected], [email protected]

How do I properly send an email to multiple recipients?

2 Answers 2

7

You can loop through a list of your recipients:

// Comma-separated list of recipients
$recipients = '[email protected], [email protected]';

// Break out recipients into an array
$recipientList = explode( ",", $recipients );

// Create the globally known things about the EmailModel
$email = new EmailModel();
$email->subject = 'My Email Subject';
$email->body    = 'My Email Body';

// Loop through each recipient in the recipient list
foreach ( $recipientList as $recipient )
{
    try
    {
        // Add a specific recipient to the email model
        $email->toEmail = $recipient;

        // Send the email
        craft()->email->sendEmail( $email );
    }
    catch ( \Exception $e )
    {
        // Do nothing
        return false;
    }
}
2
  • This worked perfectly! I'm a little bummed that "toEmail" is incapable of handling multiple email addresses (since the PHP mail function can handle multiple recipients with no problem), but your solution did the trick as a solid workaround. Thanks Ben!
    – Lindsey D
    Commented Jun 25, 2014 at 5:06
  • 1
    Why not use cc? Commented Jun 20, 2018 at 22:13
1
$email->cc = array(
    array('email' => '[email protected]', 'name' => 'Person One'),
    // ...
);

If you want emails recipients to see other recipients listed in the email, use 'cc'; otherwise, use the loop as the other answer suggested, or 'bcc'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.