發送email 帶附件的Python代碼

pythopen 9年前發布 | 3K 次閱讀 Python

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

mail_host = 'smtp.126.com' mail_user = 'xx@126.com' mail_pwd = 'xx' mail_to = 'xxzhao@gmail.com'

msg = MIMEMultipart()

att = MIMEText(open('d:\a.txt','rb').read(),'base64','gb2312') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment;filename="hello.txt"' msg.attach(att)

message = 'content part' body = MIMEText(message) msg.attach(body) msg['To'] = mail_to msg['from'] = mail_user msg['subject'] = 'this is a python test mail'

try: s = smtplib.SMTP() s.connect(mail_host) s.login(mail_user,mail_pwd)

s.sendmail(mail_user,mail_to,msg.as_string())
s.close()

print 'success'

except Exception,e: print e</pre>

 本文由用戶 pythopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!