如何在Django中使用HTML页面发送电子邮件?

时间:2019-04-30 07:17:35

标签: django

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

2 个答案:

答案 0 :(得分:0)

这是利用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

答案 1 :(得分:0)

有很多不同的解决方案,如何在Django中发送电子邮件。 如果您觉得仅使用python / django代码比较复杂,甚至可以使用php或任何脚本语言。

仅是来自自定义电子邮件订阅的电子邮件实用程序示例:

email_utility.py:

import logging, traceback
from django.urls import reverse
import requests
from django.template.loader import get_template
from django.utils.html import strip_tags
from django.conf import settings


def send_email(data):
    try:
        url = "https://api.mailgun.net/v3/<domain-name>/messages"
        status = requests.post(
            url,
            auth=("api", settings.MAILGUN_API_KEY),
            data={"from": "YOUR NAME <admin@domain-name>",
                  "to": [data["email"]],
                  "subject": data["subject"],
                  "text": data["plain_text"],
                  "html": data["html_text"]}
        )
        logging.getLogger("info").info("Mail sent to " + data["email"] + ". status: " + str(status))
        return status
    except Exception as e:
        logging.getLogger("error").error(traceback.format_exc())
        return False

不要忘记创建一个令牌,当用户单击确认链接时,我们将对其进行验证。令牌将被加密,因此没有人可以篡改数据。

token = encrypt(email + constants.SEPARATOR + str(time.time()))

还要选中此linkthis