質問

次のような Django テンプレートを使用して HTML メールを送信したいと考えています。

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

何も見つかりません send_mail, 、django-mailer は HTML テンプレートのみを送信し、動的データは送信しません。

Django のテンプレート エンジンを使用して電子メールを生成するにはどうすればよいですか?

役に立ちましたか?

解決

から ドキュメント, 、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()

おそらく電子メールには 2 つのテンプレートが必要になるでしょう。1 つは次のようなプレーン テキストで、次のテンプレート ディレクトリに保存されます。 email.txt:

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

もう 1 つは HTML 風のファイルで、以下に保存されます。 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が提供されている場合、結果の電子メールは次のようになります   text / plainのコンテンツとしてメッセージとマルチパート/代替メール   text / htmlのコンテンツ・タイプなど種類やhtml_messageます。

あなただけのことができるようにます:

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テンプレートを使用してから自分のプロジェクトのためのトランザクション、テンプレートメールのテンプレートの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',}

これは自動的にそれは少なくとも1で見つけることができない場合に文句を(通常のDjangoテンプレートdirsに/ローダーで、それぞれのプレーンとhtmlの部分は「templated_email / email.html」と「templated_email / email.txt」という名前のテンプレートを探します)これらのます。

使用EmailMultiAlternativesと二つの別のテンプレート(HTML内のプレーンテキストで1つずつ)を使用するようにrender_to_stringます:

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の簡易メールを作成しましたあなたが送りたいすべてのトランザクションメールます。

電子メールの内容とテンプレートは、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)

I任意のフィードバックを得るのが大好きだ。

あなたが書かれたとして、それを使用する場合、 ....例に誤りがあり、次のエラーが発生します:

  

<型 'exceptions.Exception'> 'dictの' オブジェクトが属性 'render_context'

を持っていません

あなたは次のインポートを追加する必要があります。

from django.template import Context

とする辞書を変更します。

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

のhttpを参照してください://docs.djangoproject。 COM / EN / 1.2 / REF /テンプレート/ API /#レンダリング・コンテキスト

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

は、私が書いたスニペットそれはあなたがデータベースに保存されているテンプレートを使用してレンダリングされた電子メールを送信することができます。例:

EmailTemplate.send('expense_notification_to_admin', {
    # context object that email template will be rendered with
    'expense': expense_request,
})
あなたのメールの動的な電子メールテンプレートを使用する場合は、

そして、あなたのデータベーステーブルに電子メールの内容を保存します。 これは、私は、データベース内の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()

これはあなたがDBに保存持っているものダイナミックHTMLテンプレートを送信します。

I容易な文脈処理で電子メールHTMLやTXTを送信するために簡単に可能にするために、このツールを使用してのような:ます。https: //github.com/divio/django-emailitする

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top