I know this is an old question, but I also know that some people are just like me and are always looking for uptodate answers, since old answers can sometimes have deprecated information if not updated.
Its now January 2020, and I am using Django 2.2.6 and Python 3.7
Note: I use DJANGO REST FRAMEWORK, the code below for sending email was in a model viewset in my views.py
So after reading multiple nice answers, this is what I did.
from django.template.loader import render_to_string
from django.core.mail import EmailMultiAlternatives
def send_receipt_to_email(self, request):
emailSubject = "Subject"
emailOfSender = "[email protected]"
emailOfRecipient = '[email protected]'
context = ({"name": "Gilbert"}) #Note I used a normal tuple instead of Context({"username": "Gilbert"}) because Context is deprecated. When I used Context, I got an error > TypeError: context must be a dict rather than Context
text_content = render_to_string('receipt_email.txt', context, request=request)
html_content = render_to_string('receipt_email.html', context, request=request)
try:
#I used EmailMultiAlternatives because I wanted to send both text and html
emailMessage = EmailMultiAlternatives(subject=emailSubject, body=text_content, from_email=emailOfSender, to=[emailOfRecipient,], reply_to=[emailOfSender,])
emailMessage.attach_alternative(html_content, "text/html")
emailMessage.send(fail_silently=False)
except SMTPException as e:
print('There was an error sending an email: ', e)
error = {'message': ",".join(e.args) if len(e.args) > 0 else 'Unknown Error'}
raise serializers.ValidationError(error)
Important! So how does render_to_string
get receipt_email.txt
and receipt_email.html
?
In my settings.py
, I have TEMPLATES
and below is how it looks
Pay attention to DIRS
, there is this line os.path.join(BASE_DIR, 'templates', 'email_templates')
.This line is what makes my templates accessible. In my project_dir, I have a folder called templates
, and a sub_directory called email_templates
like this project_dir->templates->email_templates
. My templates receipt_email.txt
and receipt_email.html
are under the email_templates
sub_directory.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'templates', 'email_templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Let me just add that, my recept_email.txt
looks like this;
Dear {{name}},
Here is the text version of the email from template
And, my receipt_email.html
looks like this;
Dear {{name}},
<h1>Now here is the html version of the email from the template</h1>
1.7
offershtml_message
insend_email
stackoverflow.com/a/28476681/953553 – andilabs