我知道这是一个老问题,但我也知道有些人和我一样,总是在寻找最新的答案,因为如果不更新旧答案,有时可能包含已弃用的信息。
现在是 2020 年 1 月,我正在使用 Django 2.2.6 和 Python 3.7
注意:我使用DJANGO REST FRAMEWORK,下面用于发送电子邮件的代码在我的views.pymodel viewset 中
所以在阅读了多个不错的答案之后,这就是我所做的。
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@domain.com"
emailOfRecipient = 'xyz@domain.com'
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)
重要! 那么render_to_string 是如何得到receipt_email.txt 和receipt_email.html 的呢?
在我的settings.py 中,我有TEMPLATES,下面是它的外观
关注DIRS,有这行os.path.join(BASE_DIR, 'templates', 'email_templates')
.这条线使我的模板可以访问。在我的 project_dir 中,我有一个名为 templates 的文件夹和一个名为 email_templates 的子目录,例如 project_dir->templates->email_templates。我的模板receipt_email.txt 和receipt_email.html 在email_templates 子目录下。
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',
],
},
},
]
让我补充一下,我的recept_email.txt 看起来像这样;
Dear {{name}},
Here is the text version of the email from template
而且,我的receipt_email.html 看起来像这样;
Dear {{name}},
<h1>Now here is the html version of the email from the template</h1>