I’m trying to send mail with SendGrid, but whenever I send an HTML formatted email, it shows the HTML tags in the email rather than formatting the HTML as desired. Here’s what I’m trying to send:
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
</p>
</body>
</html>
Here’s my code:
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()
Note: invite_user.txt contains the html above.
Any insight into why it’s not recognizing that this is HTML and formatting it accordingly? Am I missing something?
By default the Django mailer sends only the text part of an email. You need to either set it to html (which is bad practice) or use the EmailMultiAlternatives class. So, I think this is what you’re looking for really:
Also, there’s an official SendGrid python package which you might want to consider as an alternative to using the built in Django functions. Check it out here: