多測師講解自動化 _郵件傳送_高階講師肖sir
第一步、進入如下網址申請163郵箱。
第二步、註冊完之後登入、點選如下圖設定點選POP3/SMTP/IMAP。
第三步、右側點選客戶端授權密碼。
第四步、點選開啟然後點選重置授權碼。
第五步、按照如下操作編輯簡訊傳送、然後就可以
重置授權碼了、授權碼和密碼不要設定為一樣的注意點:授權碼和密碼不一致、用程式碼連線163郵件伺服器就需要用授權碼而不是密碼。
第六步、然後把init建構函式裡面的psw預設引數的值改為你自己設定的授權碼
就可以用如下的程式碼傳送郵件了。
1#coding=utf‐8 2import smtplib 3from email.mime.text import MIMEText 4from email.mime.text import MIMEText 5from email.mime.multipart import MIMEMultipart 6from email.header import Header 7import os 8 9class SendMail: 10def init (self, send_msg, 11 smtpserver="smtp.163.com", sender="[email protected]", 12psw="xxxxxx", receiver="[email protected]", #psw這個為授權碼 13port=25, attachment=None): 14# self.reportfile = reportfile 15self.send_msg = send_msg 16self.smtpserver = smtpserver 17self.sender = sender 18self.psw = psw 19self.receiver = receiver 20self.port = port 21self.attachment = attachment 22 23def send_mail(self): 24"""傳送最新的測試報告內容"""
25#開啟測試報告,讀取測試報告內容
26with open(self.send_msg, "rb") asf:
27mail_boday =f.read()
28#定義郵件
29msg =MIMEMultipart()
30msg['subject'] = Header(u"自動化測試報告", 'utf‐8')
31msg['From'] = Header(self.sender,'utf‐8')
32msg['To'] =self.receiver
33
34#新增附件
35if self.attachment !=None:
36file_name =self.attachment.split(os.path.sep)[‐1]
37att = MIMEText(open(self.attachment,"rb").read(),
38 "base64","utf‐8")
39att["Content‐Type"] ="application/octet‐stream"
40att.add_header('Content‐Disposition','attachment',
41filename =file_name)
42msg.attach(att)
43
44body = MIMEText(mail_boday, _subtype="html",_charset='utf‐8')
45msg.attach(body)
46smtp =smtplib.SMTP()
47smtp.set_debuglevel(1)
48smtp.connect(self.smtpserver,self.port)
49smtp.starttls()
50#使用者登入併發送郵件
51smtp.login(self.sender,self.psw)
52smtp.sendmail(self.sender, self.receiver,msg.as_string())
53smtp.quit()