Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sendgrid php send to multiple recipients

Tags:

php

sendgrid

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, "[email protected]");
    $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();
}
like image 977
Sahbaz Avatar asked Jan 04 '23 02:01

Sahbaz


2 Answers

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.

like image 106
Sebastian-Laurenţiu Plesciuc Avatar answered Jan 12 '23 16:01

Sebastian-Laurenţiu Plesciuc


In the end, this is how I have managed to do this and it's working good.

function sendEmail($subject, $to, $message, $cc)
{
    $from = new SendGrid\Email(null, "[email protected]");
    $subject = $subject;

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

    foreach ($cc as $value) {
        $to = new SendGrid\Email(null, $value);
        $mail->personalization[0]->addCC($to);
    }

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

    $response = $sg->client->mail()->send()->post($mail);
    echo $response->statusCode();
 }
like image 41
Sahbaz Avatar answered Jan 12 '23 16:01

Sahbaz