Подтвердить что ты не робот

Как отправить html-адрес электронной почты с помощью django с динамическим контентом?

Кто-нибудь может помочь мне отправить html-адрес электронной почты с динамическим содержимым. Один из способов - скопировать весь html-код в переменную и заполнить динамический код внутри него в представлениях Django, но это не кажется хорошей идеей, так как это очень большой html файл.

Буду признателен за любые предложения.

Спасибо.

4b9b3361

Ответ 1

Пример:

from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags

subject, from_email, to = 'Subject', '[email protected]', '[email protected]'

html_content = render_to_string('mail_template.html', {'varname':'value'}) # render with dynamic value
text_content = strip_tags(html_content) # Strip the html tag. So people can see the pure text at least.

# create the email, and attach the HTML version as well.
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

Ссылка

http://www.djangofoo.com/250/sending-html-email/comment-page-1#comment-11401

Ответ 2

Это должно делать то, что вы хотите:

from django.core.mail import EmailMessage
from django.template import Context
from django.template.loader import get_template


template = get_template('myapp/email.html')
context = Context({'user': user, 'other_info': info})
content = template.render(context)
if not user.email:
    raise BadHeaderError('No email address given for {0}'.format(user))
msg = EmailMessage(subject, content, from, to=[user.email,])
msg.send()

Подробнее см. django mail docs.

Ответ 3

Попробуйте следующее:

https://godjango.com/19-using-templates-for-sending-emails/

ссылка на образец кода

# views.py

from django.http import HttpResponse
from django.template import Context
from django.template.loader import render_to_string, get_template
from django.core.mail import EmailMessage

def email_one(request):
    subject = "I am a text email"
    to = ['[email protected]']
    from_email = '[email protected]'

    ctx = {
        'user': 'buddy',
        'purchase': 'Books'
    }

    message = render_to_string('main/email/email.txt', ctx)

    EmailMessage(subject, message, to=to, from_email=from_email).send()

    return HttpResponse('email_one')

def email_two(request):
    subject = "I am an HTML email"
    to = ['[email protected]']
    from_email = '[email protected]'

    ctx = {
        'user': 'buddy',
        'purchase': 'Books'
    }

    message = get_template('main/email/email.html').render(Context(ctx))
    msg = EmailMessage(subject, message, to=to, from_email=from_email)
    msg.content_subtype = 'html'
    msg.send()

    return HttpResponse('email_two')