邮件发送

 1 #获取最新报告
 2 def latest_report():
 3     report_dir=r'..\Website\test_report'
 4     lists=os.listdir(report_dir)
 5     lists.sort(key=lambda fn:os.path.getatime(report_dir+'/'+fn))
 6     logger.info('获取最新报告')
 7     file=os.path.join(report_dir,lists[-1])
 8     return file
 9 
10 #发送邮件
11 def send_mail(latest_report):
12     with open(latest_report,'rb') as f:
13         content=f.read()
14     f.close()
15     
16     #发送邮箱服务器
17     smtpserver='smtp.163.com'
18 
19     #发送邮箱用户名密码(密码为授权码)
20     user='**@163.com'
21     password='**'
22 
23     #发送和接收邮箱
24     sender='*@163.com'
25     recive=['*@qq.com', '*@163.com']
26 
27     #发送邮件主题和内容、HTML邮件正文
28     subject='lc_practies'
29     msg=MIMEText(content,'html','utf-8')
30     msg['Subject']=Header(subject,'utf-8')
31     msg['From']=sender
32     msg['To']=','.join(recive)
33 
34     #SSL协议端口号要使用465
35     smtp=smtplib.SMTP_SSL(smtpserver,465)
36     #HELO 向服务器标识用户身份
37     smtp.helo(smtpserver)
38     #服务器返回结果确认
39     smtp.ehlo(smtpserver)
40     #登录邮箱服务器用户名和密码
41     smtp.login(user,password)
42 
43     logger.info('发送邮件')
44     smtp.sendmail(sender,recive,msg.as_string())
45     smtp.quit()

 

 1 发送带有附件的邮件:
 2 
 3 import smtplib
 4 from email.mime.text import MIMEText
 5 from email.mime.multipart import MIMEMultipart   #用于传送附件
 6 
 7 smtpserver='smtp.163.com'
 8 
 9 user='@163.com'
10 password=''
11 
12 sender='@163.com'
13 recives=['@qq.com','@163.com']
14 
15 subject='selenium2 test'
16 content='<html><h1 style="color:red">你是最棒的!</h1></html>'
17 
18 #构造附件内容
19 send_file=open(r'C:\python35\logo.png','rb').read()
20 
21 att=MIMEText(send_file,'base64','utf-8')
22 att['Content-Type']='application/octet-stream'
23 att['Content-Disposition']='attachment;filename="logo.png"'
24 
25 #构建发送与接收信息
26 msgRoot=MIMEMultipart()
27 msgRoot.attach(MIMEText(content,'html','utf-8'))
28 msgRoot['Subject']=subject
29 msgRoot['From']=sender
30 msgRoot['To']=','.join(recives)
31 msgRoot.attach(att)
32 
33 smtp=smtplib.SMTP_SSL(smtpserver,465)
34 smtp.helo(smtpserver)
35 smtp.ehlo(smtpserver)
36 smtp.login(user,password)
37 
38 print('start send email')
39 smtp.sendmail(sender,recives,msgRoot.as_string())
40 smtp.quit()
41 print('end!')
发送带有附件的邮件

 

163邮箱发生失败的常见问题:http://help.163.com/09/1224/17/5RAJ4LMH00753VB8.html

posted on 2019-07-13 11:42  cherry_ning  阅读(117)  评论(0)    收藏  举报

导航