2013-07-15 3 views
0

저는 Python으로 전자 메일을 일부 만들고 HTML, 텍스트 및 첨부 파일을 갖고 싶습니다. 내 코드는 '작업 중'이지만 Outlook에서 출력물을 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() 

답변