3

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

$recipients = 'person@example.com';

$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 = 'person1@example.com, person2@example.com';

... and it generates an error:

Invalid address: person1@example.com, person2@example.com

How do I properly send an email to multiple recipients?

7

You can loop through a list of your recipients:

// Comma-separated list of recipients
$recipients = 'person1@example.com, person2@example.com';

// 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;
    }
}
| improve this answer | |
  • 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 Jun 25 '14 at 5:06
  • 1
    Why not use cc? – Jason Galuten Jun 20 '18 at 22:13
1
$email->cc = array(
    array('email' => 'cc1@example.com', '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'.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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