Frage

Ich möchte HTML-E-Mails senden, mit Django-Vorlagen wie folgt aus:

<html>
<body>
hello <strong>{{username}}</strong>
your account activated.
<img src="mysite.com/logo.gif" />
</body>

Ich kann nichts über send_mail finden, und django-Mailer sendet nur HTML-Vorlagen, ohne dynamische Daten.

Wie verwende ich Djangos Template-Engine E-Mails zu generieren?

War es hilfreich?

Lösung

die docs zu Bitte senden Sie HTML-E-Mail möchten Sie alternative Content-Typen verwenden, wie folgt aus:

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()

Sie werden wahrscheinlich wollen zwei Vorlagen für Ihre E-Mail - einen Nur-Text ein, dass in etwa so aussieht, gespeichert in Ihrem Vorlagenverzeichnis unter email.txt:

Hello {{ username }} - your account is activated.

und ein HTMLy ein, unter email.html gespeichert:

Hello <strong>{{ username }}</strong> - your account is activated.

Sie können dann eine E-Mail mit beiden diese Vorlagen durch Verwendung von get_template , wie folgt aus:

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()

Andere Tipps

Jungen und Mädchen!

Da Django 1.7 in send_email Methode der html_message Parameter hinzugefügt wurde.

  

html_message: Wenn html_message vorgesehen ist, wird die resultierende E-Mail   eine multipart / alternative E-Mail mit der Meldung als text / plain Inhalt   Typ und html_message als text / html Inhaltstyp.

So können Sie einfach:

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,
)

Ich habe gemacht django-Templat-E-Mail in einem Versuch, dieses Problem zu lösen, von dieser Lösung begeistert (und die Notwendigkeit, an einem gewissen Punkt, Schalter verwenden Djangos Vorlagen mit einer MailChimp usw. Reihe von Vorlagen für Transaktions-, als Templat E-Mails für mein eigenes Projekt). Es ist immer noch ein work-in-progress zwar, aber für das obige Beispiel, würden Sie tun:

from templated_email import send_templated_mail
send_templated_mail(
        'email',
        'from@example.com',
        ['to@example.com'],
        { 'username':username }
    )

Mit dem Zusatz von folgendem settings.py (das Beispiel zu vervollständigen):

TEMPLATED_EMAIL_DJANGO_SUBJECTS = {'email':'hello',}

Dies wird automatisch nach Vorlagen sucht namens ‚templated_email / email.txt‘ und ‚templated_email / email.html‘ für die Ebene und HTML-Teile jeweils in dem normalen django Vorlage dirs / Lader (beschweren, wenn es nicht mindestens einen finden von denen).

Mit EmailMultiAlternatives und render_to_string zur Verwendung von zwei alternativen Vorlagen (eine im Klartext und eine in html) zu machen:

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()

Ich habe erstellt Django Simple Mail eine einfach zu haben, anpassbare und wiederverwendbare Vorlage für jede Transaktions-E-Mail möchten Sie senden.

E-Mails Inhalte und Vorlagen können direkt von Djangos Admin bearbeitet werden.

Mit Ihrem Beispiel würden Sie Ihre E-Mail registrieren:

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)

Und es auf diese Weise senden:

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)

Ich würde gerne ein Feedback zu erhalten.

Es ist ein Fehler in dem Beispiel .... wenn Sie es als geschrieben zu verwenden, der folgende Fehler auftritt:

  

: 'dict' Objekt hat kein Attribut 'render_context'

Sie müssen den folgenden Import hinzuzufügen:

from django.template import Context

und das Wörterbuch ändern zu sein:

d = Context({ 'username': username })

Siehe http: //docs.djangoproject. com / de / 1.2 / ref / templates / api / # Rendering-a-Kontext

Django Mail-Templated ist eine feature-rich Django Anwendung E-Mails mit Django-Template-System zu senden.

Installation:

pip install django-mail-templated

Konfiguration:

INSTALLED_APPS = (
    ...
    'mail_templated'
)

Vorlage:

{% 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])

Mehr Infos: https://github.com/artemrizhov/django-mail-templated

Ich schrieb ein Schnipsel , mit dem Sie E-Mails mit in der Datenbank gespeicherten Vorlagen gemacht senden. Ein Beispiel:

EmailTemplate.send('expense_notification_to_admin', {
    # context object that email template will be rendered with
    'expense': expense_request,
})

Wenn Sie dynamische E-Mail-Vorlagen für Ihre Mail speichern Sie die E-Mail-Inhalte in Ihrer Datenbanktabelle. Das ist, was ich als HTML-Code in der Datenbank gespeichert =

<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>

Ihre Ansichten:

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()

Dies wird die dynamische senden HTML-Vorlage, was Sie speichern in Db haben.

Ich mag dieses Tool leicht zu ermöglichen, E-Mail HTML und TXT mit einfacher Kontextverarbeitung an: https: //github.com/divio/django-emailit

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top