python 傳送郵件 附帶附件
阿新 • • 發佈:2018-12-17
from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import smtplib #建立一個帶附件的例項 msg = MIMEMultipart() #構造附件1 att1 = MIMEText(open('./jsondata.py', 'rb').read(), 'base64', 'gb2312') att1["Content-Type"] = 'application/octet-stream' att1["Content-Disposition"] = 'attachment; filename="OIDFrom.doc"' #這裡的filename可以任意寫,寫什麼名字,郵件中顯示什麼名字 msg.attach(att1) #構造附件2 att2 = MIMEText(open('./demo.py', 'rb').read(), 'base64', 'gb2312') att2["Content-Type"] = 'application/octet-stream' att2["Content-Disposition"] = 'attachment; filename="OIDFrom.txt"' msg.attach(att2) #加郵件頭 msg['to'] = ";".join(['
[email protected]', '[email protected]']) # 收件人的郵箱 msg['from'] = '[email protected]' # 發件人郵箱 msg['subject'] = 'hello world' # 傳送的郵箱頭 #傳送郵件 try: server = smtplib.SMTP() server.connect('smtp.qq.com') server.login('[email protected]', 'xxxxx') #XXX為使用者名稱,XXXXX為授權碼 server.sendmail(msg['from'], msg['to'], msg.as_string()) server.quit() print ('傳送成功') except (Exception): print("完蛋咯....")