Создание шаблонов электронной почты с Django
Я хочу отправлять HTML-письма с использованием таких шаблонов Django:
<html>
<body>
hello <strong>{{username}}</strong>
your account activated.
<img src="mysite.com/logo.gif" />
</body>
Я ничего не могу найти о send_mail
и django-mailer отправляет только HTML-шаблоны без динамических данных.
Как мне использовать шаблонизатор Django для генерации электронной почты?
10 ответов
Из документов для отправки электронной почты в формате HTML вы хотите использовать альтернативные типы контента, например:
from django.core.mail import EmailMultiAlternatives
subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
Вы, вероятно, захотите два шаблона для вашей электронной почты - простой текстовый, который выглядит примерно так, хранится в каталоге шаблонов в email.txt
:
Hello {{ username }} - your account is activated.
и HTMLy, хранящийся в email.html
:
Hello <strong>{{ username }}</strong> - your account is activated.
Затем вы можете отправить электронное письмо, используя оба этих шаблона, используя get_template
, как это:
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
plaintext = get_template('email.txt')
htmly = get_template('email.html')
d = Context({ 'username': username })
subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
text_content = plaintext.render(d)
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
Мальчики и девочки!
Так как Django 1.7 в методе send_email, html_message
Параметр был добавлен.
html_message: если указан html_message, полученное в результате электронное письмо будет состоять из нескольких частей / альтернативных сообщений с сообщением в качестве типа текста / обычного содержимого и html_message в качестве типа контента text / html.
Так что вы можете просто:
from django.core.mail import send_mail
from django.template.loader import render_to_string
msg_plain = render_to_string('templates/email.txt', {'some_params': some_params})
msg_html = render_to_string('templates/email.html', {'some_params': some_params})
send_mail(
'email title',
msg_plain,
'some@sender.com',
['some@receiver.com'],
html_message=msg_html,
)
Я сделал django-templated-email в попытке решить эту проблему, вдохновленный этим решением (и необходимостью в какой-то момент переключиться с использования шаблонов django на использование mailchimp и т. Д. Набора шаблонов для транзакционных, шаблонных электронных писем для мой собственный проект). Это все еще в стадии разработки, но для приведенного выше примера вы бы сделали:
from templated_email import send_templated_mail
send_templated_mail(
'email',
'from@example.com',
['to@example.com'],
{ 'username':username }
)
С добавлением следующего в settings.py (чтобы завершить пример):
TEMPLATED_EMAIL_DJANGO_SUBJECTS = {'email':'hello',}
При этом автоматически будут искать шаблоны с именами "templated_email/email.txt" и "templated_email/email.html" для обычной и html-частей соответственно в обычных шаблонах django dirs/loaders (жалуются, если не могут найти хотя бы один из них),
Я знаю, что это старый вопрос, но я также знаю, что некоторые люди такие же, как я, и всегда ищут актуальные ответы, поскольку старые ответы иногда могут содержать устаревшую информацию, если не обновляются.
Сейчас январь 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@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>
Используйте EmailMultiAlternatives и render_to_string, чтобы использовать два альтернативных шаблона (один в виде обычного текста и один в формате HTML):
from django.core.mail import EmailMultiAlternatives
from django.template import Context
from django.template.loader import render_to_string
c = Context({'username': username})
text_content = render_to_string('mail/email.txt', c)
html_content = render_to_string('mail/email.html', c)
email = EmailMultiAlternatives('Subject', text_content)
email.attach_alternative(html_content, "text/html")
email.to = ['to@example.com']
email.send()
Я создал Django Simple Mail, чтобы иметь простой, настраиваемый и многократно используемый шаблон для каждого транзакционного электронного письма, которое вы хотите отправить.
Содержимое и шаблоны электронных писем могут быть отредактированы непосредственно от администратора django.
На вашем примере вы зарегистрируете свою электронную почту:
from simple_mail.mailer import BaseSimpleMail, simple_mailer
class WelcomeMail(BaseSimpleMail):
email_key = 'welcome'
def set_context(self, user_id, welcome_link):
user = User.objects.get(id=user_id)
return {
'user': user,
'welcome_link': welcome_link
}
simple_mailer.register(WelcomeMail)
И пошлите это так:
welcome_mail = WelcomeMail()
welcome_mail.set_context(user_id, welcome_link)
welcome_mail.send(to, from_email=None, bcc=[], connection=None, attachments=[],
headers={}, cc=[], reply_to=[], fail_silently=False)
Я хотел бы получить любую обратную связь.
send_emai()
не работал у меня, поэтому я использовал EmailMessage
здесь, в django docs.
Я включил две версии ансера:
- Только с версией электронной почты html
- С обычным текстом и версиями электронной почты в формате HTML
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
# import file with html content
html_version = 'path/to/html_version.html'
html_message = render_to_string(html_version, { 'context': context, })
message = EmailMessage(subject, html_message, from_email, [to_email])
message.content_subtype = 'html' # this is required because there is no plain text email version
message.send()
Если вы хотите включить текстовую версию своего электронного письма, измените приведенное выше следующим образом:
from django.template.loader import render_to_string
from django.core.mail import EmailMultiAlternatives # <= EmailMultiAlternatives instead of EmailMessage
plain_version = 'path/to/plain_version.html' # import plain version. No html content
html_version = 'path/to/html_version.html' # import html version. Has html content
plain_message = render_to_string(plain_version, { 'context': context, })
html_message = render_to_string(html_version, { 'context': context, })
message = EmailMultiAlternatives(subject, plain_message, from_email, [to_email])
message.attach_alternative(html_message, "text/html") # attach html version
message.send()
Мои версии plain и html выглядят так: plain_version.html:
Plain text {{ context }}
html_version.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
...
</head>
<body>
<table align="center" border="0" cellpadding="0" cellspacing="0" width="320" style="border: none; border-collapse: collapse; font-family: Arial, sans-serif; font-size: 14px; line-height: 1.5;">
...
{{ context }}
...
</table>
</body>
</html>
В примере есть ошибка.... если вы используете ее как написано, возникает следующая ошибка:
<тип 'exceptions.Exception'>: объект dict не имеет атрибута render_context
Вам нужно будет добавить следующий импорт:
from django.template import Context
и измените словарь на:
d = Context({ 'username': username })
См. http://docs.djangoproject.com/en/1.2/ref/templates/api/.
Django Mail Templated - это многофункциональное приложение Django для отправки электронных писем с помощью системы шаблонов Django.
Монтаж:
pip install django-mail-templated
Конфигурация:
INSTALLED_APPS = (
...
'mail_templated'
)
Шаблон:
{% block subject %}
Hello {{ user.name }}
{% endblock %}
{% block body %}
{{ user.name }}, this is the plain text part.
{% endblock %}
Python:
from mail_templated import send_mail
send_mail('email/hello.tpl', {'user': user}, from_email, [user.email])
Больше информации: https://github.com/artemrizhov/django-mail-templated
Если вам нужны динамические шаблоны электронной почты для вашей почты, сохраните содержимое электронной почты в таблицах базы данных. Это то, что я сохранил как HTML-код в базе данных =
<p>Hello.. {{ first_name }} {{ last_name }}. <br> This is an <strong>important</strong> {{ message }}
<br> <b> By Admin.</b>
<p style='color:red'> Good Day </p>
По вашему мнению:
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
def dynamic_email(request):
application_obj = AppDetails.objects.get(id=1)
subject = 'First Interview Call'
email = request.user.email
to_email = application_obj.email
message = application_obj.message
text_content = 'This is an important message.'
d = {'first_name': application_obj.first_name,'message':message}
htmly = FirstInterviewCall.objects.get(id=1).html_content #this is what i have saved previously in database which i have to send as Email template as mentioned above HTML code
open("partner/templates/first_interview.html", "w").close() # this is the path of my file partner is the app, Here i am clearing the file content. If file not found it will create one on given path.
text_file = open("partner/templates/first_interview.html", "w") # opening my file
text_file.write(htmly) #putting HTML content in file which i saved in DB
text_file.close() #file close
htmly = get_template('first_interview.html')
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, text_content, email, [to_email])
msg.attach_alternative(html_content, "text/html")
msg.send()
Это отправит динамический HTML-шаблон, который вы сохранили в Db.
Я написал фрагмент, который позволяет отправлять электронные письма с шаблонами, хранящимися в базе данных. Пример:
EmailTemplate.send('expense_notification_to_admin', {
# context object that email template will be rendered with
'expense': expense_request,
})
Мне нравится использовать этот инструмент, чтобы легко отправлять электронные письма HTML и TXT с простой обработкой контекста: https://github.com/divio/django-emailit