1 import smtplib 2 from email.mime.multipart import MIMEMultipart 3 from email.mime.text import MIMEText 4 from email.mime.application import MIMEApplication 5 from email.mime.image import MIMEImage 6 7 account='9xxxx65@qq.com' #發件人 8 pwd = '*******' #第三方受權碼,需登陸qq mail web頁,開通設置。 9 to = ['xxxxx@qq.com','xxxx@qq.com','xxxx@qq.com'] # 發送給多個收件人 10 host='smtp.qq.com' #主機 11 atta_path = r'C:\Users\Administrator\Desktop\testdata.txt' #附件路徑與名稱 12 name='要展現的文件名.txt' #附件顯示的名稱 13 img_path = r'C:\Users\Administrator\Desktop\dog.jpg' #顯示在正文中的圖片 14 15 # 這是正文顯示部分,其中img標籤中的src的cid:0,這個0與下文的content-ID對應。 16 17 content=''' 18 <html><body><h3> 19 Project:</h3> <p>mobile test</p> 20 <h3>Tester:</h3> <p>fish</p> 21 <h3>Date:</h3> <p>2019/12/12</p> 22 <h3>Result:</h3> <p>Pass</p> 23 <p>For morn details,you can check <a href= 'https://www.baidu.com'>Test Result</a></p> 24 <img src='cid:0' alt = 'picture'> 25 </body></html> 26 ''' 27 def sendmail(): 28 29 ret = True 30 try: 31 msg = MIMEMultipart() 32 msg['Subject'] = 'Test' 33 msg['From'] = account 34 msg['To'] = ';'.join(to) 35 36 #將圖片顯示在郵件正文中 37 fp=open(img_path,'rb') 38 img= MIMEImage(fp.read()) 39 img.add_header('Content-ID', '0') 40 msg.attach(img) 41 42 #郵件中顯示正文 43 part_text = MIMEText(content,'html','UTF-8') 44 msg.attach(part_text) 45 46 47 #這是附件部分,不一樣類型的附件,只需修更名稱、位置、要顯示的名字 48 part_att = MIMEApplication(open(atta_path,'rb').read()) 49 part_att.add_header('Content-Disposition', 'attachment', filename=name) 50 msg.attach(part_att) 51 52 #實例化一個SMTP的對象,而後登陸、發送郵件 53 s = smtplib.SMTP(host,timeout= 30) 54 s.login(account,pwd) 55 s.sendmail(account,to,msg.as_string()) 56 s.close() 57 except Exception as e: 58 ret = False 59 resaon = str(e) 60 return ret 61 62 ret = sendmail() 63 64 if ret: 65 print('send successfully') 66 else: 67 print('Error: send failed: ',reason)
如上的代碼,可實現一個簡單的郵件自動發送,且不會顯示在垃圾箱中。html