如何发送多个收件人 sendgrid V3 api Python
Posted
技术标签:
【中文标题】如何发送多个收件人 sendgrid V3 api Python【英文标题】:How to send multiple recipient sendgrid V3 api Python 【发布时间】:2018-11-09 21:59:51 【问题描述】:请大家帮忙,我正在使用 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"。
【问题讨论】:
【参考方案1】:您可以通过以下方式更新您的代码。您可以在 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】:在 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
【讨论】:
【参考方案3】:根据 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, None, subject, content)
mail.add_personalization (to_list)
response = sg.client.mail.send.post (request_body=mail.get())
return response.status_code == 202
【讨论】:
请注意,收件人都可以在电子邮件中看到对方。 (见sendgrid.com/docs/for-developers/sending-email/personalizations/…) 这对我不起作用。我收到 "python_http_client.exceptions.BadRequestsError: HTTP Error 400: Bad Request" 错误。如果我直接使用 Mail() 发送给 1 个人,它会起作用。如果这个例子仍然有效,有什么想法吗? 我想我能够弄清楚这一点。add_to()
中的Email
需要改成To
我也收到错误 400 错误请求,但在此处更改参数顺序有帮助:mail = Mail(from_email, None, subject, content)【参考方案4】:
请注意,使用此处其他答案的代码,电子邮件的收件人将在 TO 字段中看到彼此的电子邮件地址。为避免这种情况,必须为每个电子邮件地址使用单独的 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
【讨论】:
【参考方案5】:你可以传递一个字符串列表。
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)
【讨论】:
这对我不起作用。我收到以下错误 "python_http_client.exceptions.BadRequestsError: HTTP Error 400: Bad Request"。如果我只是用To('xxx@email.com')
替换 to_emails 字段,那么它可以工作,但它会破坏目的。【参考方案6】:
您可以通过在Mail
构造函数的to_emails
参数中列出多个收件人来向多个收件人发送电子邮件:
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
)
【讨论】:
以上是关于如何发送多个收件人 sendgrid V3 api Python的主要内容,如果未能解决你的问题,请参考以下文章
向大量收件人发送电子邮件的最佳实践 (Rails + SendGrid)