zoukankan      html  css  js  c++  java
  • unittest 自动发送邮件功能

    模拟发送邮件前,需要先开启SMTP服务

    操作步骤为:打开邮箱,设置--账户--开启服务

    (1)配置文件中配置如下信息

    [email]
    sender = 发送者邮箱
    sender_pwd = 授权码
    receiver = 收件人邮箱
    subject = 测试报告主题

    (2)python自带的发送邮件功能

    import smtplib
    from email.mime.multipart import MIMEMultipart # 附件
    from email.mime.text import MIMEText # 邮件文本
    from email.mime.application import MIMEApplication # 添加发送附件
    from com.myconf import conf
    
    def send_email(file_path,file_name):
    
        # 第一步连接到smtp服务器
        smtp=smtplib.SMTP_SSL("smtp.qq.com",465)
        smtp.login(conf.get('email','sender'),conf.get('email','sender_pwd'))
    
        # 第二步构建邮件
        smg=MIMEMultipart()
    
        text_smg = MIMEText(open(file_path, 'r', encoding='utf8').read(), "html") # 邮件类型:html格式,plain是文本
        smg.attach(text_smg)
    
        file_msg = MIMEApplication(open(file_path, "rb").read())
        file_msg.add_header('content-disposition', 'attachment', filename=file_name)
        smg.attach(file_msg)
    
        smg["Subject"] = conf.get('email','subject')
        smg["From"] = conf.get('email','sender')
        smg["To"] = conf.get('email','receiver')
    
    
        # 第三步发送邮件
        smtp.send_message(smg,from_addr=conf.get('email','sender'),to_addrs=conf.get('email','receiver'))
    
    
    if __name__ == '__main__':
        pass

    (3)yagmail发送邮件

      python的第三方库,需要先安装库

    • 在线安装yagmail(如已安装,无需再安装)

    python -m pip install yagmail

      安装成功:

    •  yagmail发送邮件

    import os
    import yagmail
    from com.myconf import conf
    
    def send_mail(file_path,file_name):
            yag = yagmail.SMTP(user=conf.get('email','sender'), password=conf.get('email','sender_pwd'), host='smtp.qq.com')
            subject = conf.get('email','subject')
      
            # 发送邮件
            report = os.path.join(file_path,file_name)
            yag.send(conf.get('email','sender'),conf.get('email','receiver'), report)     

    注意:给多接收者,发送多附件,用[]格式表示即可

  • 相关阅读:
    自然语言处理(NLP)入门
    OpenSSL证书认证过程
    IAR EWARM安装时报Fatal Error[Cp001]: Copy protection check, No valid license found for this product [24]
    INTEL FPGA去隔行IP DEMO
    Windows “在此系统上禁止运行脚本”解决办法
    vue中axios请求本地json文件404
    vscode tab 按钮功能变为切换按键,改回缩进功能
    引用elementUi 字体文件丢失导致图标都显示小方块
    ubuntu 添加 ll 命令
    ubuntu sudo source 时 command not found 错误
  • 原文地址:https://www.cnblogs.com/kite123/p/11563744.html
Copyright © 2011-2022 走看看