2013-07-15 283 views
0

我在Python中創建一些電子郵件,我想要HTML,文本和附件。我的代碼是「工作」,儘管它的輸出由觀示爲HTML或文本,而示出了其它「部件」(電子郵件或TXT)作爲附件。我希望擁有電子郵件和文本版本以及文件附件的強大功能。Python3 multipartmime電子郵件(文本,電子郵件和附件)

是否有一個基本的限制還是我犯了一個錯誤?

#!/usr/bin/env python3 
import smtplib,email,email.encoders,email.mime.text,email.mime.base 
from email.mime.multipart import MIMEMultipart 
from email.mime.text import MIMEText 

# me == my email address 
# you == recipient's email address 
me = "[email protected]" 
you = "[email protected]" 

# Create message container - the correct MIME type is multipart/alternative. 
msg = MIMEMultipart('mixed') 
msg['Subject'] = "msg" 
msg['From'] = me 
msg['To'] = you 

# Create the body of the message (a plain-text and an HTML version). 
text = "Hi\nThis is text-only" 
html = """\ 
<html> This is email</html> 
""" 

part1 = MIMEText(text, 'plain') 
part2 = MIMEText(html, 'html') 
#attach an excel file: 
fp = open('excelfile.xlsx', 'rb') 
file1=email.mime.base.MIMEBase('application','vnd.ms-excel') 
file1.set_payload(fp.read()) 
fp.close() 
email.encoders.encode_base64(file1) 
file1.add_header('Content-Disposition','attachment;filename=anExcelFile.xlsx') 

# Attach parts into message container. 
# According to RFC 2046, the last part of a multipart message, in this case 
# the HTML message, is best and preferred. 
msg.attach(part2) 
msg.attach(part1) 
msg.attach(file1) 

composed = msg.as_string() 

fp = open('msgtest.eml', 'w') 
fp.write(composed) 
fp.close() 

回答