【问题标题】:Sending an email using sendgrid in a Django project using an HTML template使用 HTML 模板在 Django 项目中使用 sendgrid 发送电子邮件
【发布时间】:2018-10-30 14:33:04
【问题描述】:

我正在尝试使用我的 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 电子邮件。最好,我想要某种方式来引用模板并传入上下文。有没有办法做到这一点?谢谢。

【问题讨论】:

    标签: python django sendgrid


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      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)
      

      【讨论】:

        【解决方案3】:

        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)
        

        【讨论】:

          猜你喜欢
          • 2018-10-23
          • 2019-10-29
          • 1970-01-01
          • 2020-09-08
          • 1970-01-01
          • 2018-11-08
          • 1970-01-01
          • 2016-11-03
          • 2016-07-12
          相关资源
          最近更新 更多