首页 文章

使用Django创建电子邮件模板

提问于
浏览
175

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

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

我找不到关于 send_mail 的任何内容,而django-mailer只发送HTML模板,没有动态数据 .

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

10 回答

  • -1

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

  • 1

    我写了一个snippet,它允许您发送使用存储在数据库中的模板呈现的电子邮件 . 一个例子:

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

    我创建了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)
    

    我很想得到任何反馈 .

  • 26

    男孩和女孩!

    由于Django在send_email方法中的1.7,因此添加了 html_message 参数 .

    html_message:如果提供了html_message,生成的电子邮件将是一个多部分/备用电子邮件,其中的邮件为text / plain内容类型,html_message为text / 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,
    )
    
  • 0

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

    我已经做了django-templated-email以努力解决这个问题,受到这个解决方案的启发(并且需要在某些时候从使用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',}
    

    这将分别在普通的django模板目录/加载器中自动查找名为“templated_email / email.txt”和“templated_email / email.html”的模板,用于普通django模板dirs / loaders(抱怨如果找不到其中的至少一个) .

  • 333

    Django Mail Templated 是一个功能丰富的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 %}
    

    蟒蛇:

    from mail_templated import send_mail
    send_mail('email/hello.tpl', {'user': user}, from_email, [user.email])
    

    更多信息:https://github.com/artemrizhov/django-mail-templated

  • 12

    示例中存在错误....如果您按写入方式使用它,则会发生以下错误:

    <type'exception.Exception'>:'dict'对象没有属性'render_context'

    您需要添加以下导入:

    from django.template import Context
    

    并将字典更改为:

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

    http://docs.djangoproject.com/en/1.2/ref/templates/api/#rendering-a-context

  • 0

    the docs开始,要发送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()
    
  • 3

    如果您想要邮件的动态电子邮件模板,请将电子邮件内容保存在数据库表中 . 这就是我在database =中保存为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模板 .

相关问题