2016-04-01 20 views
0

私はさまざまな種類の電子メールを送信するために使用する電子メールテンプレートを持っています。私はむしろ複数の電子メールのHTMLテンプレートを保持しないので、これを処理する最善の方法はメッセージの内容をカスタマイズすることです。これと同じように:電子メールがしかし、送信された場合Djangoの電子メールをHTMLとして

def email_form(request): 
    html_message = loader.render_to_string(
      'register/email-template.html', 
      { 
       'hero': 'email_hero.png', 
       'message': 'We\'ll be contacting you shortly! If you have any questions, you can contact us at <a href="#">[email protected]</a>', 
       'from_email': '[email protected]', 
      } 
     ) 
    email_subject = 'Thank you for your beeswax!' 
    to_list = '[email protected]' 
    send_mail(email_subject, 'message', 'from_email', [to_list], fail_silently=False, html_message=html_message) 
    return 

、HTMLコードが動作しません。メッセージは、まるで角かっこなどのように表示されます。 HTMLタグとしてレンダリングさせる方法はありますか?

+0

生成されたHTMLに適切なメタ属性がありますか?生成されたHTMLの上部の一部を貼り付けることはできますか? –

答えて

0

解決済み。それほどエレガントではありませんが、機能します。場合には誰もが好奇心だ、電子メールテンプレートに配置された変数はそのように実装する必要があります

{{ your_variable|safe|escape }} 

そして、それは動作します!みんなありがとう!

1

sendmailを使用してメールを送信する代わりに、djangoにあるEmailMultiAlternatives機能を使用できます。あなたのコードは以下のsnipetのようになります。

from django.core.mail import EmailMultiAlternatives 

def email_form(request): 
    html_message = loader.render_to_string(
      'register/email-template.html', 
      { 
       'hero': 'email_hero.png', 
       'message': 'We\'ll be contacting you shortly! If you have any questions, you can contact us at <a href="#">[email protected]</a>', 
       'from_email': '[email protected]', 
      } 
     ) 
    email_subject = 'Thank you for your beeswax!' 
    to_list = '[email protected]' 
    mail = EmailMultiAlternatives(
      email_subject, 'This is message', 'from_email', [to_list]) 
    mail.attach_alternative(html_message, "text/html") 
    try: 
     mail.send() 
    except: 
     logger.error("Unable to send mail.") 
+0

お返事ありがとうございます!私はあなたのソリューションを実装しようとしただけでなく、Django独自のドキュメントに基づいたビューで遊んでいました。残念ながらそれは働かなかった。 HTMLタグは解析されませんでした。私も "text/html"の代わりに "html"を使ってみましたが、どちらもうまくいきませんでした。 – Bob

関連する問題