zoukankan      html  css  js  c++  java
  • python之发送邮件

      项目需要,需要自动生成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)
  • 相关阅读:
    jQuery插件开发全解析(转)
    isMemberOfClass和isKindOfClass之间区别
    NSArray,NSSet,NSDictionary总结 (转)
    NSIndexPath(转)
    Maven在dos窗口中的命令
    JPA概要
    fedora的输入法
    iQQ 学习笔记2 :借助新浪微博输入验证码、远程控制退出
    使用EXCEL制作通用打印模块
    字符串加密解密方法
  • 原文地址:https://www.cnblogs.com/zoe-yan/p/11356597.html
Copyright © 2011-2022 走看看