繁体   English   中英

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM