您的位置:首页 > 编程语言 > Python开发

Python自动发送邮件功能

2018-04-03 12:00 423 查看
Python-SMTP发送邮件
SMTP(Simple Mail Transfer Protocol)是简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制新建的中转方式。
Python的smtplib模块提供了一种很方便的途径用来发送电子邮件。它对SMTP协议进行了简单的封装。我们可以使用SMTP对象的sendmail方法发送邮件。

使用SSL配置步骤:
QQ邮箱-设置–>账户-》找到POP3/IMAP 开启POP3/SMTP服务
接收邮件服务器:pop.qq.com ,使用SSL,端口 995
发送邮件服务器: smtp.qq.com,使用SSL,端口 465或 587

用户名:QQ邮箱用户名(不用加“@qq.com”)
密码:不是邮箱登录密码,是在邮箱帐号设置那生成的授权码
自己的电脑开启IIS服务步骤:
在控制面板中找到并点击“程序”选项;
然后点击“打开或关闭Windows功能”;
在功能列表中勾选 Internet Information Services 并勾选其中的“Web管理工具”如下图:


其他默认未选择的功能选择依据你自己的要求添加;
然后点击确定按钮,稍等片刻后将会为你的系统开启IIS服务功能;
然后可以在计算机—管理—服务和应用程序处打开:Internet Information Services (IIS)管理器,配置自己的SMTP电子邮件。



实例代码:
发送HTML格式的邮件
import smtplib
from email.mime.text import MIMEText
from email.header import Header

#发送邮箱服务器
stmpserver='smtp.sina.com'
#发送邮箱用户/密码
user='45***renyan@sina.com'
password='f***18'
#发送邮箱
sender='45***renyan@sina.com'
#接收邮箱
receiver='4***@qq.com'
#发送邮件主题
subject='Python email test'

#编写HTML类型的邮件正文
msg=MIMEText('<html><h1>你好!<h1><html>','html','utf-8')
msg['Subject']=Header(subject,'utf-8')
msg['From']=Header(user)

#连接发送邮件
smtp=smtplib.SMTP()
smtp.connect(stmpserver)
smtp.login(user,password)
smtp.sendmail(sender,receiver,msg.as_string())
smtplib.SMTP.quit(smtp)邮件截图:



测试报告以邮件进行发送:#自动发送测试报告
import unittest,time
from HTMLTestRunner import HTMLTestRunner
from email.mime.text import MIMEText
from email.header import Header
import smtplib
import os

#定义发送邮件
def send_mail(file_new):
f=open(file_new,'rb')
mail_body = f.read()
print(mail_body)
f.close()

msg = MIMEText(mail_body, 'html', 'utf-8')
msg["Subject"]=Header("自动化测试报告",'utf-8')

msg['From']=Header("4***@qq.com")

smtp=smtplib.SMTP_SSL("smtp.qq.com",465)
smtp.connect("smtp.qq.com")
smtp.login("4***@qq.com","ntstniahuwpabhbd**")
smtp.sendmail("4***@qq.com","4***@qq.com",msg.as_string())
smtp.quit()
print('email has send out!')

#查找测试报告目录,找到最新生成的测试报告文件
def new_report(testreport):
lists=os.listdir(testreport)
lists.sort(key=lambda fn:os.path.getatime(testreport+"\\"+fn))
file_new=os.path.join(testreport,lists[-1])
print(file_new)
return file_new

if __name__== "__main__":
test_dir = './'
test_report='D:\\testpro\\report'
discover = unittest.defaultTestLoader.discover(test_dir, pattern='test*.py')
now=time.strftime("%Y-%m-%d_%H_%M_%S")
filename=test_report+'\\'+now+'result.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