簡體   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