zoukankan      html  css  js  c++  java
  • Python(1)自动发送邮件

    python发邮件需要掌握两个模块的用法,smtplib和email,这俩模块是python自带的,只需import即可使用。smtplib模块主要负责发送邮件,email模块主要负责构造邮件。

    smtplib模块主要负责发送邮件:是一个发送邮件的动作,连接邮箱服务器,登录邮箱,发送邮件(有发件人,收信人,邮件内容)。

    email模块主要负责构造邮件:指的是邮箱页面显示的一些构造,如发件人,收件人,主题,正文,附件等。

    1.smtplib模块

    import smtplib
    
    smtp = smtplib.SMTP() 
    smtp.connect('smtp.163.com,25') 
    smtp.login(username, password) 
    smtp.sendmail(sender, receiver, msg.as_string()) 
    smtp.quit()

    2.email模块

    from email.mime.text import MIMEText
    from email.header import Header
    from email.mime.application import MIMEApplication
    from email.mime.multipart import MIMEMultipart

    我们必须把Subject,From,To添加到MIMEText对象或者MIMEMultipart对象中,邮件中才会显示主题,发件人,收件人。

    # 组装邮件内容和标题,中文需参数‘utf-8’,单字节字符不需要
            msg = MIMEMultipart()
            msg['Subject'] = Header(subject)
            msg['From'] = sender
            msg['To'] = ','.join(user_list)

    3.编写发件函数,方便调用

    自动化测试报告为HTML,以附件方式发送,

    不管什么类型的附件,都可以用MIMEApplication,MIMEApplication默认子类型是application/octet-stream

    # 发送html内容的邮件
    import smtplib
    import time
    import os
    from email.mime.text import MIMEText
    from email.header import Header
    from email.mime.application import MIMEApplication
    from email.mime.multipart import MIMEMultipart
    
    class SendMail():
        def find_new_file(self, dir):
            '''查找目录下最新的文件'''
            file_lists = os.listdir(dir)
            file_lists.sort(key=lambda fn: os.path.getmtime(dir + "\" + fn)
                            if not os.path.isdir(dir + "\" + fn)
                            else 0)
            # print('最新的文件为: ' + file_lists[-1])
            file = os.path.join(dir, file_lists[-1])
            print('完整文件路径:', file)
            return file
    
        def send_mail_html(self, file):
            '''发送html格式测试报告邮件'''
            # 发送邮箱
            sender = 'name@163.com'
            # 接收邮箱
            user_list = [
                'user@foxmail.com',
                'user@qq.com',
                'user@qq.com']
            # 发送邮件主题
            t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            subject = '接口自动化测试结果(请下载附件查看)_' + t
            # 发送邮箱服务器
            smtpserver = 'smtp.163.com'
            # 发送邮箱用户/密码
            username = 'user@163.com'
            password = 'youer_password'
            # 组装邮件内容和标题,中文需参数‘utf-8’,单字节字符不需要
            msg = MIMEMultipart()
            msg['Subject'] = Header(subject)
            msg['From'] = sender
            msg['To'] = ','.join(user_list)
            # ---这是附件部分---
            # html类型附件,不管什么类型的附件,都可以用MIMEApplication,MIMEApplication默认子类型是application/octet-stream。
            part = MIMEApplication(open(file, 'rb').read())
            part.add_header('Content-Disposition', 'attachment', filename=file)
            msg.attach(part)
            # 登录并发送邮件
            try:
                smtp = smtplib.SMTP()
                smtp.connect(smtpserver)
                smtp.login(username, password)
                smtp.sendmail(sender, user_list, msg.as_string())
            except BaseException:
                print("邮件发送失败!")
            else:
                print("邮件发送成功!")
            finally:
                smtp.quit()
    
    
    if __name__ == '__main__':
        sen = SendMail()
        dir = r'D:\api\report'  # 指定文件目录
        b = sen.find_new_file(dir)  # 查找最新的html文件
        sen.send_mail_html(b)  # 发送html内容邮件

    ps:

    python邮件发送给多人时,只有第一个人能收到的问题,

    MIMEText()["to"]的数据类型与sendmail(from_addrs,to_addrs,...)的to_addrs不同;前者为str类型,多个地址使用逗号分隔,后者为list类型。

    expects toaddrs to be a list of email addresses. (Or, of course, just use recipients in place of toaddrs.)

    参考链接:https://stackoverflow.com/questions/20509427/python-not-sending-email-to-multiple-addresses

     

    但行好事,莫问前程
  • 相关阅读:
    谷歌浏览器无法携带cookie问题
    如何言简意赅表达你需要寻求开发协助?
    vue传参params参数不能混用?
    浅谈JS变量声明和函数声明提升
    如何提高你的CSS水平
    闭包,看这一篇就够了——带你看透闭包的本质,百发百中
    Vue-给对象新增属性(使用Vue.$set())
    PHP const问题
    Linux/U-boot version with "-dirty"
    360度评估互评如何避免恶意打分
  • 原文地址:https://www.cnblogs.com/mingfan/p/10958981.html
Copyright © 2011-2022 走看看