如何发送多个收件人sendgrid V3 api Python

时间:2018-05-31 00:15:54

标签: python-3.x sendgrid

任何人请帮忙,我起诉sendgrid v3 api。但我找不到任何方式向多个收件人发送电子邮件。提前谢谢。

    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)

我想向多个收件人发送电子邮件。喜欢to_mail =" xxx@gmail.com,yyy@gmail.com"。

6 个答案:

答案 0 :(得分:4)

要将电子邮件发送到sendgrid v3中的多个Recicpent。

        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": "adilm717@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

答案 1 :(得分:3)

您可以通过以下方式更新代码。您可以在Sendgrid软件包中的mail_example.py中找到相同内容。

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

答案 2 :(得分:2)

基于Subhrajyoti Das的回答,我编写了以下代码,这是向多个收件人发送电子邮件的mail_example.py示例的简化版本。

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, subject, None, content)
    mail.add_personalization (to_list)
    response = sg.client.mail.send.post (request_body=mail.get())

    return response.status_code == 202

答案 3 :(得分:1)

请注意,使用此处其他答案的代码,电子邮件的收件人将在“收件人”字段中看到彼此的电子邮件地址。为避免这种情况,必须为每个电子邮件地址使用单独的Personalization对象:

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

答案 4 :(得分:1)

您可以通过在to_emails构造函数的Mail参数中列出多个收件人来向他们发送电子邮件:

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)

使用此配置,每个收件人将能够看到电子邮件中列出的彼此。为避免这种情况,请使用is_multiple参数告诉Sendgrid为每个收件人创建一个新的Personalization

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
)

答案 5 :(得分:0)

您可以传递字符串列表。

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)