
發(fā)送郵件問題網(wǎng)上案例很多,基本的都差不多,這是我的代碼:
# coding=utf-8
__author__ = 'xcma'
import os
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from LogMainClass import Log #這是我自定義的log類,如果本地沒有可以刪掉
from ReadConfig import Read_config#自定義的讀取配置文件類
from Utils import ABSpath#自定義獲取當前執(zhí)行文件的:絕對路徑
import smtplib
log = Log("Email.py") #還是log類的命名,可以將log相關的全部刪掉
def send_mail(send_file_path):
"""
:param send_file_path: 測試報告文件路徑
:return:
"""
config_file_path = ABSpath()+"/Src/Conf/Config.ini"
category = "email"
#讀取配置文件中相關信息
smtpserver = Read_config.return_specific_str(category, "mail_host", config_file_path)
smtpuser = Read_config.return_specific_str(category, "mail_user", config_file_path)
password = Read_config.return_specific_str(category, "mail_pass", config_file_path)
#拼裝接收人 --遍歷接收人配置項
mailto = []
receive_category = "email_receiver"
#返回所有接收人
receivers = Read_config.return_options(receive_category, config_file_path)
for i in receivers:
#找到每個接收人對應的郵箱地址
receiver = Read_config.return_specific_str(receive_category, i, config_file_path)
#將每個人對應的郵箱地址插入mailto列表中
mailto.append(receiver)
msg = MIMEMultipart()
#定義發(fā)送人
msg['From'] = smtpuser
#定義接收郵件對象 --群發(fā)
msg['To'] = ",".join(mailto)
#郵件標題
msg['Subject'] = Header('自動化測試報告', 'utf-8').encode()
msg["Accept-Language"] = "zh-CN"
msg["Accept-Charset"] = "ISO-8859-1,utf-8"
content = "<h2>!若想查看用例明細,請下載附件查看</h2>"
try:
sendfile = send_file_path +new_report(send_file_path)
file_name = new_report(send_file_path)
#將html中內(nèi)容貼在郵件正文中
fp = open(sendfile, 'rb')
msg.attach(MIMEText(content+fp.read(), 'html', 'utf-8'))
fp.close()
# 添加附件
fp = open(sendfile, 'rb')
part = MIMEApplication(fp.read())
fp.close()
part.add_header('Content-Disposition', 'attachment', filename=file_name)
msg.attach(part)
#發(fā)送郵件
server = smtplib.SMTP_SSL(smtpserver, 465)
server.set_debuglevel(1)
server.login(smtpuser, password)
server.sendmail(smtpuser, mailto, msg.as_string())
server.quit()
except Exception as msg:
log.exception(u'郵件發(fā)送失敗')
print msg
def new_report(testreport):
''' 將文件按照名字時間順序排序,輸出文件名字
:param testreport:測試報告存放路徑
:return:
'''
try:
lists = os.listdir(testreport)
log.debug(u'當前路徑中文件列表'+str(lists))
lists.sort(key=lambda fn: os.path.getmtime(testreport + '/' + fn))
file_new = os.path.join(lists[-1])
#返回最新生成的文件名稱
log.info(u'將要發(fā)送的測試報告文件:'+file_new)
return file_new
except Exception as msg:
print msg
raise
-
雖說都差不多,但是這里認為主要有幾個需要注意的地方:
1.通過qq郵箱ssl方式發(fā)送郵件的,需要將端口號修改為:465,并不是默認的
2.郵件群發(fā),必須要使用 msg['To'] = ",".join(mailto) 這種形式,mailto是列表形式
3.mailto通過讀取配置文件直接讀取是不成功的,必須通過遍歷組裝才能解決(目前我的解決辦法)
4.雖然可以將html文件貼在郵件中,但是在查看郵件時,通常的郵箱是不支持js操作的,所以原本html支持js的(比如:樣式隱藏、展示操作)在郵箱中查看只能看見默認展開項(當然可以通過修改html的方式,達到目的)
5.郵箱中預覽附件會出現(xiàn)中文亂碼-目前我沒有解決方案,只是盡量將中文換成英文,避免問題暴露
-
配置文件/Src/Conf/Config.ini

配置文件.png