Search code examples
phpsendgrid

Sendgrid php send to multiple recipients


I have simple sendgrid php script to send email, only issue here is that i need to add more recipients, so this code works only for one recipient, i was looking at official documentation but was unable to find any useful info, is there anyone who knows how and what i need to change here to add more recipients/emails.

function sendEmail($subject, $to, $message) {
    $from = new SendGrid\Email(null, "sample@email.com");
    $subject = $subject;

    $to = new SendGrid\Email(null, $to);
    $content = new SendGrid\Content("text/html", $message);
    $mail = new SendGrid\Mail($from, $subject, $to, $content);

    $apiKey = 'MY_KEY';
    $sg = new \SendGrid($apiKey);

    $response = $sg->client->mail()->send()->post($mail);
    echo $response->statusCode();
}

Solution

  • The SendGrid\Mail class supports adding multiple to addresses through the SendGrid\Personalization class.

    You can see an example here: https://github.com/sendgrid/sendgrid-php/blob/master/examples/helpers/mail/example.php#L31-L35

    Think of a Personalization as the envelope for your email. It holds the recipient's addresses and other similar data. Each Sendgrid\Mail object, must have at least one Personalization.

    Through the constructor you are using, a Personalization object is already created for you, see here: https://github.com/sendgrid/sendgrid-php/blob/master/lib/helpers/mail/Mail.php#L951-L958

    You can create a Mail object without this and later add your own Personalization.