我想发送html电子邮件,使用Django模板,像这样:

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

我找不到任何关于send_mail的东西,django-mailer只发送HTML模板,没有动态数据。

如何使用Django的模板引擎生成电子邮件?


当前回答

如果您想要为您的邮件设置动态电子邮件模板,请将电子邮件内容保存在数据库表中。 这是我保存为HTML代码在database =

<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模板。

其他回答

在文档中,要发送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.

还有一个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()

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

我喜欢使用这个工具,允许轻松地发送电子邮件HTML和TXT与简单的上下文处理:https://github.com/divio/django-emailit

我写了一个代码片段,允许您发送使用存储在数据库中的模板渲染的电子邮件。一个例子:

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

我创建了Django Simple Mail,为你想发送的每一封事务性电子邮件提供了一个简单的、可定制的和可重用的模板。

邮件内容和模板可以直接从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)

我很乐意得到任何反馈。