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

时间:2017-11-28 23:18:18

标签: python email smtp mime

我正在编写一个脚本,用于创建以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()

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

1 个答案:

答案 0 :(得分:2)

在标准文档中,请参阅模块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