尝试使用Django send_mail和SendGrid发送电子邮件

时间:2013-01-29 20:54:40

标签: django sendgrid

我正在尝试使用SendGrid发送邮件,但每当我发送HTML格式的电子邮件时,它都会在电子邮件中显示HTML标记,而不是根据需要格式化HTML。这是我要发送的内容:

<html>
<head></head>
<body>
  <p>Hi!<br>
     How are you?<br>
  </p>
</body>
</html>

这是我的代码:

 def send(self, group=None):
        current_site = Site.objects.get_current()
        domain = unicode(current_site.domain)
        ctx = {
            "group": group,
            "signup_code": self,
            "domain": domain,
        }
        msg = MIMEMultipart('alternative')
        subject = render_to_string("signup_codes/invite_user_subject.txt", ctx)
        msg['subject'] = render_to_string("signup_codes/invite_user_subject.txt", ctx)
        message = render_to_string("signup_codes/invite_user.txt", ctx)
        text = "Hi!\nHow are you?\n"
        part1 = MIMEText(text, 'plain')
        part2 = MIMEText(message,'html')
        msg.attach(part1)
        msg.attach(part2)
        send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.email])
        self.sent = datetime.datetime.now()
        self.save()

注意:invite_user.txt包含上面的html。

为什么它没有认识到这是HTML并相应地格式化它?我错过了什么吗?

1 个答案:

答案 0 :(得分:3)

默认情况下,Django邮件程序仅发送电子邮件的文本部分。您需要将其设置为html(这是不好的做法)或使用EmailMultiAlternatives类。所以,我认为这正是你真正想要的:

from django.core.mail import EmailMultiAlternatives

def send(self, group=None):
  current_site = Site.objects.get_current()
  domain = unicode(current_site.domain)
  ctx = {
      "group": group,
      "signup_code": self,
      "domain": domain,
  }

  subject = render_to_string("signup_codes/invite_user_subject.txt", ctx)
  text_content = "Hi!\nHow are you?\n"
  html_content = render_to_string("signup_codes/invite_user.txt", ctx)

  msg = EmailMultiAlternatives(subject, text_content, settings.DEFAULT_FROM_EMAIL, [self.email])
  msg.attach_alternative(html_content, "text/html")

  msg.send()

此外,还有一个官方的SendGrid python包,您可能需要考虑将其作为使用内置Django函数的替代方法。在这里查看:

  

https://github.com/sendgrid/sendgrid-python/