如何在项目目录中附加html文件并将其作为邮件发送?

我正在尝试发送在测试用例执行后生成的覆盖率报告,该报告是在htmlcov文件夹中生成的,

import os
from django.conf import settings
from utils import email_utils


def pytest_sessionfinish(session,exitstatus):
    to = ['xyz123@gmail.com']
    body = 'test'
    subject = 'coverage test'
    attachment = 'htmlcov/index.html'
    coverage_html = os.path.join(settings.BASE_DIR + '/' + attachment)
    email_utils.send_email_with_attachment(to,body,subject,coverage_html,'application/html','index.html')

在执行此操作时出现以下错误:

ERROR | 2020-03-12 10:07:57,180 | MainThread | email_utils.send_email_with_attachment.69 | a bytes-like object is required,not 'str'
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/django/core/mail/message.py",line 342,in send
    return self.get_connection(fail_silently).send_messages([self])
  File "/usr/local/lib/python3.5/dist-packages/sgbackend/mail.py",line 66,in send_messages
    mail = self._build_sg_mail(email)
  File "/usr/local/lib/python3.5/dist-packages/sgbackend/mail.py",line 125,in _build_sg_mail
    base64_attachment = base64.b64encode(attachment[1])
  File "/usr/lib/python3.5/base64.py",line 59,in b64encode
    encoded = binascii.b2a_base64(s)[:-1]
TypeError: a bytes-like object is required,not 'str'

我使用if语句检查了路径中是否存在文件,是否存在,这是否与我在此处处理文件的方式有关?什么是正确的方法?

这是使用以下功能发送电子邮件的功能:

def send_email_with_attachment(to_email,attachment_content=None,main_type=None,file_name=None):
    data = {'from_email': settings.DEFAULT_FROM_EMAIL,'to': to_email,'subject': subject,'body': body}

    logger.info("sending email")
    email = EmailMessage(**data)
    email.content_subtype = "html"

    if attachment_content:
        email.attach(file_name,attachment_content,main_type)
    try:
        email.send()
        logger.info("Email sent")
    except BaseException as e:
        logger.exception(e)
ufo748 回答:如何在项目目录中附加html文件并将其作为邮件发送?

您好,Junior将您的html文件放在模板文件夹中,并编写以下代码,并确保在您编写模板设置的settings.py文件中。

import os
from django.conf import settings
from utils import email_utils


def pytest_sessionfinish(session,exitstatus):
    to = ['xyz123@gmail.com']
    body = 'test'
    subject = 'coverage test'
    attachment = "index.html"
    coverage_html = os.path.join(settings.BASE_DIR + '/' + attachment)
    email_utils.send_email_with_attachment(to,body,subject,coverage_html,'application/html',"index.html")
本文链接:https://www.f2er.com/2654416.html

大家都在问