Отправьте HTML по электронной почте с повторяющимися данными модели - PullRequest
0 голосов
/ 23 апреля 2019

Я пытаюсь настроить оповещение по электронной почте, которое отправляется раз в неделю.Я намерен установить 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 ]

2 голосов
/ 23 апреля 2019

Вы можете использовать метод render_to_string из шаблонов django для рендеринга вашего HTML и контекста в строку, подобную этой.

from django.template import loader

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

Отправьте текст с вашей электронной почтой, как хотите.

1 голос
/ 23 апреля 2019

Почему бы вам не использовать почтовую систему 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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...