SendGridAPIClient():Python中发送HTML格式的邮件模板示例代码
发布时间:2023-12-15 09:55:01
下面是一个使用SendGrid API发送HTML格式的邮件模板的示例代码:
import sendgrid
from sendgrid.helpers.mail import Mail, Email, To, Content
def send_html_email(api_key, to_email, from_email, subject, html_content):
sg = sendgrid.SendGridAPIClient(api_key=api_key)
from_email = Email(from_email)
to_email = To(to_email)
content = Content("text/html", html_content)
mail = Mail(from_email, to_email, subject, content)
response = sg.send(mail)
print(response.status_code)
# 使用示例
api_key = 'YOUR_SENDGRID_API_KEY'
to_email = 'recipient@example.com'
from_email = 'sender@example.com'
subject = 'Sample HTML Email'
html_content = '''
<html>
<body>
<h1>Hello!</h1>
<p>This is a sample HTML email.</p>
</body>
</html>
'''
send_html_email(api_key, to_email, from_email, subject, html_content)
这段代码使用了SendGrid Python库来发送邮件。首先,我们创建一个SendGridAPIClient对象,需要传入SendGrid API密钥。然后,我们定义了发送邮件的相关信息,包括收件人、发件人、主题和邮件内容。邮件内容使用了HTML格式,通过Content类设置类型为"text/html"的邮件内容。最后,我们使用send方法发送邮件,并打印出发送的响应状态码。
在使用示例中,您需要替换YOUR_SENDGRID_API_KEY为您的SendGrid API密钥,并设置收件人、发件人、主题和邮件内容。通过调用send_html_email函数,您可以发送包含HTML格式内容的邮件。
这是一个简单的示例代码,您可以根据自己的需求进行扩展和修改。同时,您可以使用SendGrid API文档(https://sendgrid.com/docs/api-reference/)了解更多关于SendGrid API的详细信息和功能。
