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

问题描述 投票:0回答:1

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

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


    def pytest_sessionfinish(session, exitstatus):
        to = ['[email protected]']
        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, body, subject, 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)
        print(email, '------email-----')
    try:
        email.send()
        logger.info("Email sent")
    except BaseException as e:
        logger.exception(e)
python django attachment email-attachments coverage.py
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.