【问题标题】:How to send Email with html page in Django?如何在 Django 中发送带有 html 页面的电子邮件?
【发布时间】:2019-04-30 07:17:34
【问题描述】:

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

【问题讨论】:

    标签: django


    【解决方案1】:

    在 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将被加密,任何人都无法篡改数据。

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

    同时检查linkthis

    【讨论】:

    • “to”是我们要发送电子邮件的人员列表
    • 是的。顺便说一句,“数据”是字典类型。
    • 请查看此链接以获取完整解决方案:pythoncircle.com/post/657/…
    【解决方案2】:

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

    【讨论】:

    • 这里我们必须在代码本身中给接收者发送电子邮件,我不需要。它应该是动态的
    • 没你说的那么简单
    猜你喜欢
    • 2013-11-11
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 2016-11-27
    • 2011-04-16
    • 2011-01-04
    • 1970-01-01
    相关资源
    最近更新 更多