📅  最后修改于: 2023-12-03 15:34:56.260000             🧑  作者: Mango
如果你需要向多个收件人发送电子邮件并使用 SendGrid 作为邮件服务提供商,可以使用 SendGrid 的 Python API 在 Python 中发送电子邮件。
使用 SendGrid Python API 发送电子邮件之前,需要先安装 SendGrid Python API,可以通过以下命令进行安装:
pip install sendgrid
在发送电子邮件前,需要准备好邮件的内容。邮件内容需要包括收件人、主题、正文和发件人等信息。
以下是一个示例邮件内容:
to_email = ['recipient1@example.com', 'recipient2@example.com']
sender_email = 'sender@example.com'
subject = 'Testing SendGrid Python API'
body = 'This is a test email sent using SendGrid Python API.'
使用准备好的邮件内容,可以使用 SendGrid Python API 发送电子邮件。以下是一个示例代码片段:
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
to_email = ['recipient1@example.com', 'recipient2@example.com']
sender_email = 'sender@example.com'
subject = 'Testing SendGrid Python API'
body = 'This is a test email sent using SendGrid Python API.'
message = Mail(
from_email=sender_email,
to_emails=to_email,
subject=subject,
html_content=body)
try:
sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(e.message)
以上代码将使用 SendGrid Python API 发送邮件。你需要将代码中的to_email
、sender_email
、subject
、body
和SENDGRID_API_KEY
替换为你实际的信息。
下面是示例代码片段的 Markdown 格式:
```python
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
to_email = ['recipient1@example.com', 'recipient2@example.com']
sender_email = 'sender@example.com'
subject = 'Testing SendGrid Python API'
body = 'This is a test email sent using SendGrid Python API.'
message = Mail(
from_email=sender_email,
to_emails=to_email,
subject=subject,
html_content=body)
try:
sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(e.message)