P113305A009D8M
P113305A009D8M

Reputation: 374

How to send multiple recipient sendgrid V3 api Python

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 = " [email protected], [email protected]".

Upvotes: 21

Views: 18810

Answers (6)

Rafael Adnet Pinho
Rafael Adnet Pinho

Reputation: 493

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

Upvotes: 7

Adiii
Adiii

Reputation: 59896

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": "[email protected]"
                }, {
                    "email": "[email protected]"
                }],
            "subject": "Multiple recipent Testing"
            }
        ],
        "from": {
            "email": "[email protected]"
        },
        "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

Upvotes: 9

Luke Taylor
Luke Taylor

Reputation: 9561

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='[email protected]',
    to_emails=[To('[email protected]'), To('[email protected]')],
    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='[email protected]',
    to_emails=[To('[email protected]'), To('[email protected]')],
    subject='Subject line',
    text_content='This is the message of your email',
    is_multiple=True  # Avoid listing all recipients on the email
)

Upvotes: 23

ST7
ST7

Reputation: 2432

You can pass a list of strings.

message = Mail(
            from_email='[email protected]',
            to_emails=['[email protected]', '[email protected]'],
            subject='subject',
            html_content='content')

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

Upvotes: 6

asmaier
asmaier

Reputation: 11746

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

Upvotes: 16

Subhrajyoti Das
Subhrajyoti Das

Reputation: 2710

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("[email protected]",
                              "Example User"),
                            Email("[email protected]",
                              "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

Upvotes: 7

Related Questions