编写python的smtplib库发送邮件代码(简洁-原创)
Posted iruance_bill
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了编写python的smtplib库发送邮件代码(简洁-原创)相关的知识,希望对你有一定的参考价值。
import smtplib #python自带 from email.mime.text import MIMEText from email.header import Header class Sendemail(): def sendqqemail(self): emailo=smtplib.SMTP() #SMTP类的实例化对象 emailo.connect('smtp.qq.com',25) #smtp的默认端口号 sendmsg_contents=input('请输入邮件的文字内容:') try: emailo.login('46080****@qq.com','oimmpyaa****bjbe') #oimmpyaa****bjbe是发件人的邮箱的16位授权码,在邮箱的设置-账户-pop3/smtp中发送短信获取。 mg= MIMEText(f'<html><h1>sendmsg_contents</h1></html>','html','utf-8')#MIME(Multipurpose Internet Mail Extensions)多用途互联网邮件扩展类型 subject = '666python学习-爱软测同学们使用QQ邮箱给163邮箱发消息' mg['subject'] = Header(subject,'utf-8') mg['from'] = '46080****@qq.com' mg["to"] = 'cherry****@163.com'#mg['subject'],mg['from'],mg["to"] 这三个为固定格式,不能少,依次为邮件主题,发件人,收件人 emailo.sendmail(mg['from'],mg["to"],mg.as_string()) #邮件内容必须为字符串格式,as_string()方法不能少 except SMTPAuthenticationError as e1: print('邮件的授权码填写错误'.format(e1)) except SMTPDataError as e2: print('邮件标题,收件人,发件人数据格式错误'.format(e2)) finally: print('邮件发送成功!!') emailo.quit() if __name__ == '__main__': s=Sendemail() s.sendqqemail()
Python + HTMLTestRunner + smtplib 完成测试报告生成及发送测试报告邮件
一下代码是自己结合教材,并结合以往用到的实例编写的代码,可以做为参考
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from HTMLTestRunner import HTMLTestRunner from email.header import Header import unittest import time,os #==============定义发送邮件 =============== def send_mail(file_new): f = open(file_new,‘rb‘) #读取测试报告正文 mail_body = f.read() f.close() # 发送邮箱服务器 smtpserver = "smtp.163.com" # 发件人邮箱 sender = ‘[email protected]‘ # 接收人邮箱 receiver = ‘[email protected]‘ # 发送邮箱用户信息 username = ‘[email protected]‘ # 客户端授权码 password = ‘WMQyyj2018‘ #通过 模块构造的带附件的邮件如图 msg = MIMEMultipart() #编写html类型的邮件正文,MIMEtext()用于定义邮件正文 #发送正文 text = MIMEText(mail_body, ‘html‘, ‘utf-8‘) text[‘Subject‘] = Header(‘自动化测试报告‘, ‘utf-8‘) msg.attach(text) #发送附件 #Header()用于定义邮件标题 msg[‘Subject‘] = Header(‘自动化测试报告‘, ‘utf-8‘) msg_file = MIMEText(mail_body, ‘html‘, ‘utf-8‘) msg_file[‘Content-Type‘] = ‘application/octet-stream‘ msg_file["Content-Disposition"] = ‘attachment; filename="TestReport.html"‘ msg.attach(msg_file) # 如果只发正文的话,上面的代码 从password 下面到这段注释上面 # 全部替换为下面的两行代码即可,上面的代码是增加了发送附件的功能。 # text = MIMEText(mail_body, ‘html‘, ‘utf-8‘) # text[‘Subject‘] = Header(‘自动化测试报告‘, ‘utf-8‘) #连接发送邮件 # smtp = smtplib.SMTP() # smtp.connect(smtpserver) # smtp.login(username, password) # smtp.sendmail(‘[email protected]‘, ‘[email protected]‘, msg.as_string()) # smtp.quit() # print("email has send out !") #一样的逻辑,不一样的写法导致上面的发送失败,下面这种发送成功,所以要使用msg[‘from‘]这种写法 msg[‘from‘] = ‘[email protected]‘ # 发送邮件的人 msg[‘to‘] = ‘[email protected]‘ # smtp = smtplib.SMTP(‘smtp.163.com‘, 25) # 连接服务器 smtp = smtplib.SMTP() smtp.connect(‘smtp.163.com‘) smtp.login(username, password) # 登录的用户名和密码 smtp.sendmail(msg[‘from‘], msg[‘to‘], msg.as_string()) # 发送邮件 smtp.quit() print(‘sendmail success‘) #======================查找最新的测试报告========================== def new_report(testreport): #方式1: # lists = os.listdir(testreport) # lists.sort(key = lambda fn: os.path.getmtime(testreport + ‘\\‘ + fn)) # file_new = os.path.join(testreport,lists[-1]) # print(file_new) # return file_new #方式2: dirs = os.listdir(testreport) dirs.sort() newreportname = dirs[-1] print(‘The new report name: {0}‘.format(newreportname)) file_new = os.path.join(testreport, newreportname) return file_new if __name__ == ‘__main__‘: test_dir = os.path.join(os.getcwd(),‘test_case‘) #test_report = "D:/SProgram/PySpace/wmq/SendHtmlMail/report" test_report = os.path.join(os.getcwd(), ‘report‘) discover = unittest.defaultTestLoader.discover(test_dir,pattern=‘test*.py‘) now = time.strftime("%Y-%m-%d-%H_%M_%S") filename = test_report+‘/result_‘+now+‘.html‘ fp = open(filename,‘wb‘) runner = HTMLTestRunner(stream=fp,title="测试报告",description=‘用例执行情况:‘) runner.run(discover) fp.close() new_report = new_report(test_report) send_mail(new_report)
以上是关于编写python的smtplib库发送邮件代码(简洁-原创)的主要内容,如果未能解决你的问题,请参考以下文章