2012-09-14 89 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) 
相關問題