Я знаю, что это старый вопрос, но я также знаю, что некоторые люди такие же, как я, и всегда ищут актуальные ответы, поскольку старые ответы иногда могут содержать устаревшую информацию, если не обновляются.
Сейчас январь 2020 года, я использую Django 2.2.6 и Python 3.7
Примечание. Я использую DJANGO REST FRAMEWORK, приведенный ниже код для отправки электронной почты был в модель просмотра в моем views.py
Итак, прочитав несколько хороших ответов, я сделал это.
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)
Важно! Так как же 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>
person
manpikin
schedule
06.01.2020
1.7
предлагаетhtml_message
вsend_email
stackoverflow.com/a/28476681/953553 - person andilabs   schedule 12.02.2015