Python 發送帶附件的郵件


以下代碼發送附件-文本文件和圖片

 

#!/usr/bin/env python
#-*-coding:utf-8-*-

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

_user = "yy@qq.com"
_pwd = "授權碼"
# _to = "ft_clover@163.com"
_recer=["aa@qq.com","bb@163.com",]


#創建一個帶附件的實例
msg=MIMEMultipart()
msg["Subject"] = " don't panic"
msg["From"] = _user
msg["To"] = ",".join(_recer)#區別與給一個人發,指定某個人用 msg["To"] = _to 多個人用.join


#郵件正文內容
msg.attach(MIMEText('假如你立志要能言善辯,請先學會專注聆聽。做一個有趣的人,並對他人感興趣。問對方樂於回答的問題,鼓勵他們談論自己的經歷。'
                    '請記住,你的談話對象並不關心你和你的問題,而對他們自己、他們的欲望和煩惱要感興趣得多。他的牙疼遠比異國餓殍遍地的飢荒更重要,他脖子上的癤子也遠比非洲的四十次地震更讓人心煩。所以下次開口之前,請先想想這一點。','plain', 'utf-8'))
#構造附件1,傳輸當前目錄下的圖片.txt文件
att1=MIMEText(open('jmeter.txt','rb').read(),'base64','utf-8')
att1['Content-Type']='application/octet-stream'
att1['Content-Disposition']='attachment;filename="demo.txt"' #filename 填什么,郵件里邊展示什么

#構造附件2,傳輸當前目錄下的圖片.jpg文件
att2=MIMEText(open('圖片.jpg','rb').read(),'base64','utf-8')
att2['Content-Type']='application/octet-stream'
att2['Content-Disposition']='attachment;filename="demo.jpg"' #filename填什么,郵件里邊展示什么

msg.attach(att1)
msg.attach(att2)


try:
    s=smtplib.SMTP_SSL("smtp.qq.com",465)
    s.login(_user,_pwd)
    s.sendmail(_user,_recer,msg.as_string())
    s.quit()
    print("Success!")
except smtplib.SMTPException as e:
    print("Failed,%s"%e)

 

執行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM