Этот код из приложения django_messages.Даже, хотя шаблон должен быть html, я все равно получаю необработанный HTML-код в элементе электронной почты. Что нужно сделать в этом случае для отправки как текстовой версии, так и корректной работы Версия HTML?django add html email template
{% load i18n %}
{% load url from future %}
{% blocktrans with recipient=message.recipient sender=message.sender %}Hello {{ recipient }},
you received a private message from {{ sender }} with
the following contents:{% endblocktrans %}
{{ message.body|safe }}
--
{% blocktrans %}Sent from {{ site_url }}{% endblocktrans %}
Выше new_message.html файлу
Ниже фактический код для отправки электронной почты
def new_message_email(sender, instance, signal,
subject_prefix=_(u'New Message: %(subject)s'),
template_name="messages/new_message.html",
default_protocol=None,
*args, **kwargs):
"""
This function sends an email and is called via Django's signal framework.
Optional arguments:
``template_name``: the template to use
``subject_prefix``: prefix for the email subject.
``default_protocol``: default protocol in site URL passed to template
"""
if default_protocol is None:
default_protocol = getattr(settings, 'DEFAULT_HTTP_PROTOCOL', 'http')
if 'created' in kwargs and kwargs['created']:
try:
current_domain = Site.objects.get_current().domain
subject = subject_prefix % {'subject': instance.subject}
message = render_to_string(template_name, {
'site_url': '%s://%s' % (default_protocol, current_domain),
'message': instance,
})
if instance.recipient.email != "":
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
[instance.recipient.email,])
except Exception as e:
#print e
pass #fail silently
if 'created' in kwargs and kwargs['created']:
try:
current_domain = Site.objects.get_current().domain
subject = subject_prefix % {'subject': instance.subject}
message = render_to_string(template_name, {
'site_url': '%s://%s' % (default_protocol, current_domain),
'message': instance,
})
if instance.recipient.email != "":
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
[instance.recipient.email,])
except Exception as e:
#print e
pass #fail silently
Это новый код, который я попробовал на следующем примере, но он не работает.
if 'created' in kwargs and kwargs['created']:
try:
current_domain = Site.objects.get_current().domain
subject = subject_prefix % {'subject': instance.subject}
html_content = render_to_string(template_name, {
'site_url': '%s://%s' % (default_protocol, current_domain),
'message': instance,
})
if instance.recipient.email != "":
text_content = strip_tags(html_content)
msg = EmailMultiAlternatives(subject, text_content, settings.DEFAULT_FROM_EMAIL,
[instance.recipient.email,])
msg.attach_alternative(html_content, "text/html")
send_mail(msg)
except Exception as e:
#print e
pass #fail silently
Знание html_message, но с использованием более старой версии, чем 1.7+. Я много раз смотрел на ссылку, но не знал, как применить ее в этом конкретном коде выше. – user3760940
Вам просто нужно заменить свой 'send_mail()' на пример в документах и отредактировать тему, тело и т. Д. По мере необходимости. Какую часть вы не понимаете? – Alasdair
Пожалуйста, см. Оригинальный вопрос. В конце я разместил новый код. – user3760940