首页 > 解决方案 > 如何在 Django 中发送带有 html 页面的电子邮件?

问题描述

我是 Django 的新手!我不知道如何在 Django 中发送电子邮件。我参考了 Django 文档,但它对我没有帮助。我需要将带有 html 页面的电子邮件发送给不同的用户。在 models.py 中,我有两个值 Name 和 Email。当我单击按钮时,html 页面应发送到相应用户的电子邮件

标签: django

解决方案


这是一个利用 django send_mail 的简单示例:

import smtplib
from django.core.mail import send_mail
from django.utils.html import strip_tags
from django.template.loader import render_to_string


#user will be a queryset like:
users = User.objects.all() # or more specific query
subject = 'Subject'
from_email = 'from@xxx.com'

def send_email_to_users(users,subject,from_email):
    full_traceback = []
    for user in users:
        to = [user.email] # list of people you want to sent mail to.
        html_content = render_to_string('mail_template.html', {'title':'My Awesome email title', 'content' : 'Some email content', 'username':user.username}) # render with dynamic context you can retrieve in the html file
        traceback = {}
        try:
            send_mail(subject,strip_tags(html_content),from_email, to, html_message=html_content, fail_silently=False)
            traceback['status'] = True

        except smtplib.SMTPException as e:
            traceback['error'] = '%s (%s)' % (e.message, type(e))
            traceback['status'] = False

        full_traceback.append(traceback)
    errors_to_return = []
    error_not_found = []
    for email in full_traceback:
        if email['status']:
            error_not_found.append(True)
        else:
            error_not_found.append(False)
            errors_to_return.append(email['error'])

    if False in error_not_found:
        error_not_found = False
    else:
        error_not_found = True
    return (error_not_found, errors_to_return)



#really naive view using the function on top
def my_email_view(request,user_id):
    user = get_object_or_404(User, pk=user_id)
    subject = 'Subject'
    from_email = 'myemail@xxx.com'
    email_sent, traceback = send_email_to_users(user, subject, from_email)

    if email_sent:
        return render(request,'sucess_template.html')

    return render(request,'fail_template.html',{'email_errors' : traceback})

在您的模板 mail_template.html 中:

<h1>{{title}}</h1>
<p>Dear {{username}},</p>
<p>{{content}}</p>

并且不要忘记在 settings.py 中设置电子邮件设置:https ://docs.djangoproject.com/fr/2.2/ref/settings/#email-backend

来自文档的发送邮件: https ://docs.djangoproject.com/fr/2.2/topics/email/#send-mail

文档中的 Render_to_string:https ://docs.djangoproject.com/fr/2.2/topics/templates/#django.template.loader.render_to_string


推荐阅读