取名 Send_email.py 代码如下:
#coding:utf-8
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import os
def send_email():
smtpserver = "smtp.163.com" #发送服务器
port = 0 #端口
sender = "13****82@163.com" #寄件人账号
psw = "c****x6" #授权码密码(在邮箱设置里面设置)
receiver = ['17***6*8@qq.com','1****00@qq.com'] #接受者
subject= "主题:这是一个自动化测试报告"
#创建一个带附件的实例
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] =';'.join(receiver) #多人接受时写法
msg['Subject'] =subject
#构造附件:
#先读附件
test_report = os.path.join(os.path.dirname(os.path.realpath(__file__)),"result.html")
with open(test_report, "rb") as fp:
mail_body = fp.read()
# 邮件正文内容:
# msg.attach(MIMEText("这是一个带附件的邮件", 'plain', 'utf-8')) #正文是以文字存在时
msg.attach(MIMEText(mail_body, 'html', 'utf-8')) #正文以html存在时
#以下是写附件的格式:
att = MIMEText(mail_body,"base64",'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"]='attachment;filename="report_test.html"' #filename是重名附件名字
msg.attach(att)
#同事兼容163和QQ邮箱的登录方法
try:
smtp=smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(sender,psw) #登录
except:
smtp = smtplib.SMTP_SSL(smtpserver,port)
smtp.login(sender,psw)
#smtp.login(sender,psw) #登录
smtp.sendmail(sender,receiver,msg.as_string()) #发送 as_string 作为字符串类型发送msg['to'].split(",")
smtp.quit()
if __name__=="__main__":
send_email()