20

Anyone please help, I am using sendgrid v3 api. But I cannot find any way to send an email to multiple recipients. Thank in advance.

    import sendgrid
    from sendgrid.helpers.mail import *

    sg = sendgrid.SendGridAPIClient(apikey="SG.xxxxxxxx")
    from_email = Email("FROM EMAIL ADDRESS")
    to_email = Email("TO EMAIL ADDRESS")
    subject = "Sending with SendGrid is Fun"
    content = Content("text/plain", "and easy to do anywhere, even with Python")
    mail = Mail(from_email, subject, to_email, content)
    response = sg.client.mail.send.post(request_body=mail.get())
    print(response.status_code)
    print(response.body)
    print(response.headers)

I want to send email to multiple recipient. Like to_mail = " xxx@gmail.com, yyy@gmail.com".

Pythonic
  • 2,091
  • 3
  • 21
  • 34
P113305A009D8M
  • 344
  • 1
  • 4
  • 13

6 Answers6

17

You can send an email to multiple recipients by listing them in the to_emails parameter of the Mail constructor:

from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import *

message = Mail(
    from_email='sender@example.com',
    to_emails=[To('test@example.com'), To('test2@example.com')],
    subject='Subject line',
    text_content='This is the message of your email',
)

sg = SendGridAPIClient(SENDGRID_API_KEY)
response = sg.send(message)

With this configuration, each recipient will be able to see each other listed on the email. To avoid this, use the is_multiple parameter to tell Sendgrid to create a new Personalization for each recipient:

message = Mail(
    from_email='sender@example.com',
    to_emails=[To('test@example.com'), To('test2@example.com')],
    subject='Subject line',
    text_content='This is the message of your email',
    is_multiple=True  # Avoid listing all recipients on the email
)
Luke Taylor
  • 8,631
  • 8
  • 54
  • 92
  • This bit `to_emails=[To('test@example.com'), To('test2@example.com')]` is exactly what I was looking for. Thanks. – Banty Jul 26 '22 at 10:37
16

Note that with the code of the other answers here, the recipients of the email will see each others emails address in the TO field. To avoid this one has to use a separate Personalization object for every email address:

def SendEmail():
    sg = sendgrid.SendGridAPIClient(api_key="YOUR KEY")
    from_email = Email ("FROM EMAIL ADDRESS")

    person1 = Personalization()
    person1.add_to(Email ("EMAIL ADDRESS 1"))
    person2 = Personalization()
    person2.add_to(Email ("EMAIL ADDRESS 2"))

    subject = "EMAIL SUBJECT"
    content = Content ("text/plain", "EMAIL BODY")
    mail = Mail (from_email, subject, None, content)
    mail.add_personalization(person1)
    mail.add_personalization(person2)
    response = sg.client.mail.send.post (request_body=mail.get())

    return response.status_code == 202
asmaier
  • 11,132
  • 11
  • 76
  • 103
9

To send email to multiple recicpent in sendgrid v3.

        import time
        import sendgrid
        import os

        print "Send email to multiple user"

        sg = sendgrid.SendGridAPIClient(apikey='your sendrid key here')
        data = {
        "personalizations": [
            {
            "to": [{
                    "email": "adiii@gmail.com"
                }, {
                    "email": "youremail@gmail.com"
                }],
            "subject": "Multiple recipent Testing"
            }
        ],
        "from": {
            "email": "Alert@gmail.com"
        },
        "content": [
            {
            "type": "text/html",
            "value": "<h3 style=\"color: #ff0000;\">These checks are silenced please check dashboard. <a href=\"http://sensu.mysensu.com/#/silenced\" style=\"color: #0000ff;\">Click HERE</a></h3>  <br><br> <h3>For any query please contact DevOps Team<h3>"
            }
        ]
        }
        response = sg.client.mail.send.post(request_body=data)
        print(response.status_code)
        if response.status_code == 202:
            print "email sent"
        else:
            print("Checking body",response.body)
            

https://libraries.io/github/sendwithus/sendgrid-python

Adiii
  • 54,482
  • 7
  • 145
  • 148
7

You can update your code in the below way. You can find the same in mail_example.py present in Sendgrid's package.

personalization = get_mock_personalization_dict()
mail.add_personalization(build_personalization(personalization))

def get_mock_personalization_dict():
    """Get a dict of personalization mock."""
    mock_pers = dict()
    mock_pers['to_list'] = [Email("test1@example.com",
                              "Example User"),
                            Email("test2@example.com",
                              "Example User")]
    return mock_pers

def build_personalization(personalization):
    """Build personalization mock instance from a mock dict"""
    mock_personalization = Personalization()
    for to_addr in personalization['to_list']:
        mock_personalization.add_to(to_addr)
    return mock_personalization
Subhrajyoti Das
  • 2,685
  • 3
  • 21
  • 36
7

Based on Subhrajyoti Das answer, I wrote the following code, that is a simpler version of the mail_example.py example of sending email to multiple recipient.

def SendEmail():
    sg = sendgrid.SendGridAPIClient(api_key="YOUR KEY")
    from_email = Email ("FROM EMAIL ADDRESS")

    to_list = Personalization()
    to_list.add_to (Email ("EMAIL ADDRESS 1"))
    to_list.add_to (Email ("EMAIL ADDRESS 2"))
    to_list.add_to (Email ("EMAIL ADDRESS 3"))

    subject = "EMAIL SUBJECT"
    content = Content ("text/plain", "EMAIL BODY")
    mail = Mail (from_email, None, subject, content)
    mail.add_personalization (to_list)
    response = sg.client.mail.send.post (request_body=mail.get())

    return response.status_code == 202
Community
  • 1
  • 1
  • 1
    Note that the recipients will all be able to see each other on the email. ( see https://sendgrid.com/docs/for-developers/sending-email/personalizations/#sending-the-same-email-to-multiple-recipients) – asmaier Feb 05 '19 at 18:05
  • 1
    This is not working for me. I am getting a **"python_http_client.exceptions.BadRequestsError: HTTP Error 400: Bad Request"** error. It works if I sent to only 1 person using Mail() directly. Any ideas if this example still works? – Nikhil Gupta May 10 '20 at 23:19
  • I guess I was able to figure this out. The `Email` in `add_to()` needs to be changed to `To` – Nikhil Gupta May 11 '20 at 00:05
  • 1
    I also got Error 400 Bad Request, but changing the sequence of parameters here helped: mail = Mail(from_email, None, subject, content) – Eugene Chabanov May 21 '20 at 19:53
6

You can pass a list of strings.

message = Mail(
            from_email='sender@email.com',
            to_emails=['xxx@email.com', 'yyy@email.com'],
            subject='subject',
            html_content='content')

sg = SendGridAPIClient('SENDGRID_API_KEY')
response = sg.send(message)
ST7
  • 2,272
  • 1
  • 20
  • 13
  • 1
    This does not work for me. I get the following error **"python_http_client.exceptions.BadRequestsError: HTTP Error 400: Bad Request"**. If I just replace the to_emails field with `To('xxx@email.com')`, then it works, but it defeats the purpose. – Nikhil Gupta May 10 '20 at 23:26