我想使用 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()

您可能需要两个电子邮件模板 - 一个看起来像这样的纯文本模板,存储在您的模板目录下 email.txt:

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

和一个 HTMLy ,存储在 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,所得到的电子邮件将   与消息作为文本/无格式内容的多部分/替代电子邮件   类型和html_message作为文本/ html内容类型。

所以你可以:

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的模板化的电子邮件在努力解决这个问题,该解决方案(从使用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',}

这会自动寻找对纯名为“templated_email / email.txt”和“templated_email / email.html”模板和HTML份分别在正常django的模板目录/装载机(抱怨,如果它不能至少一个找到那些)。

使用EmailMultiAlternatives和render_to_string利用的两种可供选择的模板(一个纯文本,一个在HTML):

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)

我希望得到任何反馈。

有在例如一个错误....如果使用它作为写入,会出现以下错误:

  

<型 'exceptions.Exception'>: '字典' 对象没有属性 'render_context'

您将需要添加以下导入:

from django.template import Context

和更改字典是:

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

请参阅 HTTP://docs.djangoproject。 COM / EN / 1.2 / REF /模板/ API /#渲染-A-上下文

<强> Django的邮件模板化 是功能丰富的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

如果你想动态电子邮件模板为您的邮件,然后保存在数据库表中的电子邮件内容。 这就是我保存在数据库=

的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模板,你有什么保存。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top