发送带有重复模型数据的html电子邮件

时间:2019-04-23 17:13:46

标签: django

我正在尝试设置每周发送一次的电子邮件警报。我打算为此功能设置一个cronjob,这样它就会这样做。

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


def send_email():
    try:
        msg = MIMEMultipart('alternative')
        msg['From'] = "<email>"
        msg['To'] = "<email>"
        msg['Subject'] = "sub"

        html = """
        <html>
        <head></head>
        <body>
            <p> hello</p>
        </body>
        </html>
        """
        part1 = MIMEText(html, 'html')

        msg.attach(part1)
        mail = smtplib.SMTP("smtp.email.client", 587, timeout=20)
        mail.starttls()

        recepient = ['<email>']

        mail.login('<email>', '<password>')
        mail.sendmail("fromemail@domain.com", recepient, msg.as_string())
        mail.quit()

    except Exception as e:
        raise e

我试图在我的项目中让html镜像我的模板之一,并且在这个模板中,我遍历模型数据以创建图表。

views.py

class TestView(LoginRequiredMixin, TemplateView):
    template_name = "test.html"

    def get_context_data(self, **kwargs):
        context = super(TestView, self).get_context_data(**kwargs)
        context['testrail'] = TestRail.objects.all()
        return context

test.html

    <body>
<h1>4.2.0 Test Plan</h1>
{% for x in testrail %}
<h3>{{x.component}}</h3>
<table class="tg">
<tr>
    <th class="tg-baqh"></th>
    <th class="tg-0lax">#</th>
  </tr>
      <tr>
    <td class="tg-hmp3">Total</td>
    <td class="tg-hmp3">{{x.total_count}}</td>
  </tr>
  <tr>
    <td class="tg-hmp3">Passed</td>
    <td class="tg-hmp3">{{x.passed_count}}</td>
  </tr>
    <tr>
    <td class="tg-0lax">Untested</td>
    <td class="tg-0lax">{{x.untested_count}}</td>
  </tr>
     <tr>
    <td class="tg-0lax">Failed</td>
    <td class="tg-0lax">{{x.failed_count}}</td>
  </tr>
     <tr>
    <td class="tg-0lax">Reviewed</td>
    <td class="tg-0lax">{{x.reviewed_count}}</td>
  </tr>
     <tr>
    <td class="tg-0lax">Harness Failures</td>
    <td class="tg-0lax">{{x.test_harness_issue_count}}</td>
  </tr>
     <tr>
    <td class="tg-0lax">Product Failures</td>
    <td class="tg-0lax">{{x.bug_failure_count}}</td>
  </tr>
    <tr>
    <td class="tg-0lax">Coverage %</td>
    <td class="tg-0lax">{{x.coverage_percentage}}%</td>
  </tr>
    <tr>
    <td class="tg-0lax">Passed %</td>
    <td class="tg-0lax">{{x.passed_percentage}}%</td>
  </tr>
    <tr>
    <td class="tg-0lax">Reviewed %</td>
    <td class="tg-0lax">{{x.reviewed_percentage}}%</td>
  </tr>
    <tr>
    <td class="tg-0lax">Harness Failure %</td>
    <td class="tg-0lax">{{x.harness_percentage}}%</td>
  </tr>
    <tr>
    <td class="tg-0lax">Product Failure %</td>
    <td class="tg-0lax">{{x.product_failure_percentage}}%</td>
  </tr>
  </table>

现在,由于要使用模型数据和css文件,因此我很难弄清如何镜像上面的内容。

我不一定需要.css文件才能工作,但想知道如何能够在电子邮件的html部分显示模型数据。

我如何能够在电子邮件中迭代和显示模型数据(例如在模板中)?

2 个答案:

答案 0 :(得分:2)

您可以使用Django模板中的render_to_string方法将html和上下文呈现为这样的字符串。

from django.template import loader

text = loader.render_to_string(<TEMPLATE_NAME>, {'x': <MODEL_INSTANCE>})

根据需要发送带有电子邮件的文本。

答案 1 :(得分:1)

为什么不使用Django的邮件系统。它使用smtplib,但可以避免您处理细节的麻烦。只需在settings.py

中添加基本设置
# SMTP Host settings
EMAIL_HOST = ''
EMAIL_PORT = ''

# if your SMTP host needs authentication
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''

# Mail is sent using the SMTP host and port specified in the EMAIL_HOST and
# EMAIL_PORT settings. The EMAIL_HOST_USER and EMAIL_HOST_PASSWORD settings, if
# set, are used to authenticate to the SMTP server, and the EMAIL_USE_TLS and
# EMAIL_USE_SSL settings control whether a secure connection is used.

那么您可以简单地做到:

   from django.template.loader import render_to_string
   from django.core.mail import EmailMessage

   def send_email():
        context = {}
        subject = "subject"
        from_email = "from@email.com"
        body_template = "template.html"
        body = render_to_string(body_template, context).strip()
        to_emails = ["list of emails"]
        email = EmailMessage(subject, body, from_email, to_emails)
        email.content_subtype = "html"
        email.send()