2014-09-26 33 views
0

我有一些小問題。使用SMTP從Python發送附件郵件

我使用:

import smtplib 
from email.MIMEMultipart import MIMEMultipart 
from email.MIMEText import MIMEText 

msg = MIMEMultipart() 
msg['From'] = '[email protected]' 
msg['To'] = '[email protected]' 
msg['Subject'] = 'simple email in python' 
message = 'here is the email' 
msg.attach(MIMEText(message)) 

mailserver = smtplib.SMTP('smtp.gmail.com',587) 
# identify ourselves to smtp gmail client 
mailserver.ehlo() 
# secure our email with tls encryption 
mailserver.starttls() 
# re-identify ourselves as an encrypted connection 
mailserver.ehlo() 
mailserver.login('[email protected]', 'mypassword') 

mailserver.sendmail('[email protected]','[email protected]',msg.as_string()) 

mailserver.quit() 

和寄託都還好 - 但我想添加一個TXT文件附件。你可以幫我嗎?

+0

請不要使用所有的帽子。它就像是一樣。 – MattDMo 2014-09-26 17:55:03

回答

0

你可以做到這樣的:

filename = ... 
with open(filename,'r') as f: 
    message = MIMEText(f.read()) 
    message.add_header('Content-Disposition', 'attachment', filename=filename) 
    msg.attach(message) 

其中msgMIMEMultiPart對象。

0

我找到答案,但感謝很多! :)

filename='/www/pages/DANE/komunikaty.txt' 
    fp=open(filename,'rb') 
    att = email.mime.application.MIMEApplication(fp.read(),_subtype="txt") 
    fp.close() 
    att.add_header('Content-Disposition','attachment',filename=filename) 
    msg.attach(att)