Skip to content

Instantly share code, notes, and snippets.

@akmamun
Last active December 6, 2021 15:15
Show Gist options
  • Save akmamun/1a1269310e027965b53e0f40fa8191bd to your computer and use it in GitHub Desktop.
Save akmamun/1a1269310e027965b53e0f40fa8191bd to your computer and use it in GitHub Desktop.
Django send email for both html template and text
from django.conf import settings
from django.core.mail import EmailMessage
from django.template.loader import get_template
class EmailService:
def __init__(self):
self.from_email = settings.EMAIL_HOST
def send_email(self, subject: str, template: str, data=None):
"""
description: send email
params: subject, message or html template
"""
try:
from_mail = self.from_email
recipient_list = [data.get('recipient_email')]
content = get_template(template).render(data)
message = EmailMessage(subject,
content,
from_mail,
recipient_list)
message.content_subtype = "html" # content is now text/html
return message.send()
except Exception as ex:
print(ex)
email_service = EmailService()
# usage
# data = {}
# email_service.send_email(subject="email subject",
# template="template_name.html", data=data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment