2012-09-14 55 views
1

我试图使用Python电子邮件客户端发送电子邮件。我已经写了下面的代码,但是它将attachemnt作为正文发送,而不是作为附件发送。Python:附件显示在电子邮件正文中

可能有人请告诉我什么是错的代码:

# Import smtplib for the actual sending function 
import smtplib 

# Here are the email package modules we'll need 
from email.mime.text import MIMEText 
from email.mime.multipart import MIMEMultipart 
from email.mime.application import MIMEApplication 


EMAIL_LIST = ['[email protected]'] 

# Create the container (outer) email message. 
msg = MIMEMultipart() 
msg['Subject'] = 'THIS DOES NOT WORK' 
# me == the sender's email address 
# family = the list of all recipients' email addresses 
msg['From'] = '[email protected]' 
print EMAIL_LIST 
print '--------------------' 
print ', '.join(EMAIL_LIST) 
msg['To'] = ', '.join(EMAIL_LIST) 
msg.preamble = 'THIS DOES NOT WORK' 


fileName = 'c:\\p.trf' 
with open(fileName, 'r') as fp: 
    attachment = MIMEText(fp.read()) 
    fp.close() 
    msg.add_header('Content-Disposition', 'attachment', filename=fileName) 
    msg.attach(attachment) 


# Send the email via our own SMTP server. 
s = smtplib.SMTP('localhost') 
s.sendmail('[email protected]', EMAIL_LIST, msg.as_string()) 
s.quit() 

回答

0

对于附件,你应该使用,MIMEBase是这样的:

import os 
from email import encoders 
from email.mime.base import MIMEBase 

with open(fileName,'r') as fp: 
    attachment = MIMEBase('application','octet-stream') 
    attachment.set_payload(fp.read()) 
    encoders.encode_base64(attachment) 
    attachment.add_header('Content-Disposition','attachment',filename=os.path.split(fileName)[1]) 
    msg.attach(attachment) 
相关问题