项目需要,需要自动生成PDF测试报告。经过对比之后,选择使用了reportlab模块。 项目背景:开发一个测试平台,供测试维护测试用例,执行测试用例,并且生成测试报告(包含PDF和excel),将生成的测试报告以邮件的形式发送相关人。
发送邮件代码如下:
# 邮件发送 class EmailReportor: def __init__(self): self.smtpSender = 'xxx@xxx.com' self.smtpAddr = 'smtp.exmail.qq.com' self.smtpLogin = '授权码' def __replaceformat__(self, formator, **args): for k in args.keys(): rk = "{" + k + "}" if formator.__contains__(rk): formator = formator.replace(rk, str(args[k])) return formator def makeEmail(self, sender, receiver, ccReceiver, nick_name, subject, htmlBody, fileAttach, filePath, filename): from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import formataddr mimeMail = MIMEMultipart() mimeMail.add_header("Date", time.strftime("%A, %d %B %Y %H:%M")) if nick_name is not None: mimeMail['From'] = formataddr([nick_name, sender]) else: mimeMail.add_header("From", sender) mimeMail.add_header("To", receiver) mimeMail.add_header("Reply-To", sender) if ccReceiver is not None and ccReceiver != "": mimeMail.add_header("cc", ccReceiver) mimeMail.add_header("Subject", subject) mimeMail.attach(MIMEText(_text=htmlBody.encode("utf8"), _subtype="html", _charset="utf8")) if fileAttach == 'PDF': if len(filename) > 0: # 支持多文件附件 for i in range(len(filename)): att = MIMEText(open(filePath + filename[i], 'rb').read(), 'base64', 'utf-8') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="' + filename[i] + '"' mimeMail.attach(att) return mimeMail def sendEmail(self, mailto, mailcc=None, nick_name=None, subject=None, htmlBody=None, mimeMail=None, mailfrom=None, fileAttach=None, filePath=None, filename=None): sender, smtpAddr, smtpLogin = self.smtpSender, self.smtpAddr, self.smtpLogin if mimeMail is None: mimeMail = self.makeEmail(sender if Sql.isEmpty(mailfrom) else mailfrom, mailto, mailcc, nick_name, subject, htmlBody, fileAttach, filePath, filename).as_string() import base64 try: receiver = [] for r in (mailto + ";" + ("" if mailcc is None else mailcc)).replace(',', ';').split(";"): if r.strip() != "": receiver.append(r) if len(receiver) == 0: raise Exception("请填写收件人") smtpAccount, smtpPasswd = base64.decodestring(smtpLogin).split("/") import smtplib smtp = smtpAddr.split(':') smtpServer = smtp[0] smtpPort = int(ObjOperation.tryGetVal(smtp, 1, 25)) smtpClient = smtplib.SMTP(smtpServer, smtpPort) # smtpClient.set_debuglevel(1) try: smtpClient.ehlo() smtpClient.login(smtpAccount, smtpPasswd) except: pass smtpClient.sendmail(sender, receiver, mimeMail) smtpClient.quit() return '邮件发送成功: %s' % ";".join(receiver) except Exception as ex: return str(ex)