使用HTML模板在Django项目中使用sendgrid发送电子邮件

时间:2018-05-20 23:32:31

标签: python django sendgrid

我正在尝试使用我的Sendgrid帐户从我的Django项目发送电子邮件。目前,我正在通过以下方式发送电子邮件:

import sendgrid
import os
from sendgrid.helpers.mail import *

sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
from_email = Email("test@example.com")
to_email = Email("test@example.com")
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)

代码取自此链接: https://github.com/sendgrid/sendgrid-python

现在,我想在内容部分执行此操作,而不是执行文本/纯文本电子邮件,我想发送格式正确的HTML电子邮件。最好,我想要一些方法来引用模板并传入上下文。有没有办法做到这一点?感谢。

3 个答案:

答案 0 :(得分:3)

这应该很简单。您需要使用render_to_string。它需要一个请求,模板和上下文字典,就像render一样,但会生成一个字符串。然后将其传递给Content并将mime类型设置为text\html

答案 1 :(得分:0)

django中的结帐模板 - https://docs.djangoproject.com/en/2.0/topics/templates/

发送模板,您可以使用

from django.template.loader import get_template

html_content = get_template('html_sample.html').render({'foo': 'bar'})   
content = Content("text/html", html_content)

答案 2 :(得分:0)

forgot_password_template.html 是html文件/模板,您可以选中

from django.core.mail import send_mail, EmailMessage
from django.template.loader import render_to_string

message = render_to_string('forgot_password_template.html', {'bar': foo})
user.email_user("Send test email", message)
相关问题