Last active
December 6, 2021 15:15
-
-
Save akmamun/1a1269310e027965b53e0f40fa8191bd to your computer and use it in GitHub Desktop.
Django send email for both html template and text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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