MIME - 发送带有 HTML 文件作为附件的电子邮件?

MIME- sending an email with an HTML file as an attachment?

我正在编写一个脚本来创建多个以 HTML 格式保存的交互式图表。我想编写代码将这些 HTML 文件作为附件发送到电子邮件中。我似乎找不到任何关于此的文档,只有关于如何在电子邮件中嵌入 HTML 的说明,这不是我想要的。我只是想附上文件,就像我附上JPG图片或PDF文件一样。

到目前为止,我的代码只嵌入了 HTML:

import lxml.html
import smtplib
import sys
import os

page = 'report.html'

root = lxml.html.parse(page).getroot()
root.make_links_absolute()

content = lxml.html.tostring(root)

message = """From: <me@gmail.com>
To: <you@gmail.com>
MIME-Version: 1.0
Content-type: text/html
Subject: %s

%s""" %(page, content)


s = smtplib.SMTP('localhost')
s.sendmail('me@gmail.com', ['you@gmail.com'], message)
s.quit()

感谢您的帮助。我希望找到一种动态方式来发送多种格式的文件,这样我就不必担心发送不同类型文件的不同功能。

在标准文档中,请参阅模块 email

的第三个示例

https://docs.python.org/3.6/library/email.examples.html#email-examples

# Import smtplib for the actual sending function
import smtplib

# And imghdr to find the types of our images
import imghdr

# Here are the email package modules we'll need
from email.message import EmailMessage

# Create the container email message.
msg = EmailMessage()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = ', '.join(family)
msg.preamble = 'Our family reunion'

# Open the files in binary mode.  Use imghdr to figure out the
# MIME subtype for each specific image.
for file in pngfiles:
    with open(file, 'rb') as fp:
        img_data = fp.read()
    msg.add_attachment(img_data, maintype='image',
                                 subtype=imghdr.what(None, img_data))

# Send the email via our own SMTP server.
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)

编辑: 对于其他文件,您可以获得 maintypesubtype

import mimetypes

filename = 'file.html'
ctype, encoding = mimetypes.guess_type(filename)
maintype, subtype = ctype.split("/", 1)

print(maintype, subtype)

# text html