• python3使用SMTP发送邮件


    环境:python3 ,IDE : pycharm

    非常奇怪的是,用163发送邮件,如果电脑连校园网发送,会被当成垃圾邮件拒绝

    如果用手机开热点就可以正常发送

    代码如下

     1 #!/usr/bin/python
     2 # -*- coding: utf-8 -*-
     3 import time
     4 import smtplib
     5 from email.mime.text import MIMEText
     6 from email.mime.multipart import MIMEMultipart
     7 
     8 # 第三方 SMTP 服务
     9 mail_host = ""      # SMTP服务器a
    10 mail_user = ""                  # 用户名
    11 mail_pass = ""               # 授权密码,非登录密码
    12 
    13 sender = ''    # 发件人邮箱(最好写全, 不然会失败)
    14 receivers = ['']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
    15 
    16 title = '163邮件测试'  # 邮件主题
    17 content = '我用Python'
    18 
    19 def sendEmail():
    20     message = MIMEMultipart()
    21     message.attach(MIMEText(content, 'plain', 'utf-8'))
    22     message['From'] = "{}".format(sender)  # 发件人
    23     message['To'] = ",".join(receivers)  # 收件人
    24     message['Subject'] = title  # 邮件主题
    25 
    26     try:
    27         smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # 启用SSL发信, 端口一般是465
    28         smtpObj.login(mail_user, mail_pass)  # 登录验证
    29         smtpObj.sendmail(sender, receivers, message.as_string())  # 发送
    30         print("mail has been send successfully.")
    31     except smtplib.SMTPException as e:
    32         print(e)
    33 
    34 if __name__ == '__main__':
    35     print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    36     sendEmail()
    View Code

    还有就是,针对QQ邮箱的一系列代码,是这次测试的作业,自动生成测试报告,并自动发送添加报告为附件的邮件

    简单的软件测试代码 test_job.py:

    # -*- coding: utf-8 -*-
    
    import unittest
    
    
    def sum(a, b):
        return a + b
    
    
    def sub(a, b):
        return a - b
    
    
    class TestZuoYe(unittest.TestCase):
    
        @classmethod
        def setUpClass(cls):
            print('')
    
        @classmethod
        def tearDownClass(cls):
            print('')
    
    
        def test_Sum(self):
            self.assertEqual(4, sum(3, 1))
            self.assertNotEqual(8, sum(3, 1))
    
        def test_Sub(self):
            self.assertEqual(2, sub(3, 1))
            self.assertNotEqual(8, sub(3, 1))
    
    if __name__ == '__main__':
        unittest.main()
    View Code

    然后是发送邮件 sendmail.py:

     1 # -*- coding:utf-8 -*-
     2 
     3 from HTMLTestRunner import HTMLTestRunner
     4 from email import encoders
     5 from email.mime.text import MIMEText
     6 from email.header import Header
     7 from email.mime.multipart import MIMEMultipart
     8 from email.mime.base import MIMEBase
     9 import smtplib
    10 import unittest
    11 import time
    12 import os
    13 
    14 
    15 # 定义发送邮件
    16 def send_mail(file_new):
    17 
    18     msg_from = ''  # 发送方邮箱
    19     passwd = ''  # 填入发送方邮箱的授权码
    20     msg_to = ''  # 收件人邮箱
    21 
    22     msg_subject = ""  # 邮件主题
    23     msg_content = ""  # 邮件正文
    24 
    25     msg = MIMEMultipart()
    26     # 邮件正文是MIMEText:
    27     msg.attach(MIMEText(msg_content, 'plain', 'utf-8'))
    28 
    29     # # 构造附件,传送当前目录下的 .txt 文件
    30     # att1 = MIMEText(open('mybook.txt', 'rb').read(), 'base64', 'utf-8')
    31     # att1["Content-Type"] = 'application/octet-stream'
    32     # att1["Content-Disposition"] = 'attachment; filename="file1.txt"'
    33     # msg.attach(att1)
    34 
    35     # 添加附件,发送一个 .html文件
    36     with open(file_new, 'rb') as f:
    37         mime = MIMEBase('html', 'html')
    38         # 加上必要的头信息
    39         mime.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_new))
    40         mime.add_header('Content-ID', '<0>')
    41         mime.add_header('X-Attachment-Id', '0')
    42         # 把附件的内容读进来
    43         mime.set_payload(f.read())
    44         # 用Base64编码
    45         encoders.encode_base64(mime)
    46         msg.attach(mime)
    47 
    48     msg['Subject'] = Header(msg_subject, 'utf-8')  # 主题
    49     msg['From'] = msg_from
    50     msg['To'] = msg_to
    51 
    52     try:
    53         s = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 邮件服务器及端口号
    54         s.login(msg_from, passwd)
    55         s.sendmail(msg_from, msg_to, msg.as_string())
    56         print('发送成功!')
    57     except s.SMTPException as e:
    58         print("发送失败!")
    59     finally:
    60         s.quit()
    61 
    62 
    63 # 查找测报告目录,找到最新生成的测试报告文件
    64 def new_report(testreport):
    65     lists = os.listdir(testreport)
    66     lists.sort(key=lambda fn: os.path.getmtime(testreport + "\" + fn))
    67     file_new = os.path.join(testreport, lists[-1])
    68     print(file_new)
    69     return file_new
    70 
    71 
    72 if __name__ == '__main__':
    73     # 测试用例存放位置
    74     test_dir = 'E:ALL_DemoPy_DemoJob3ExamCase'
    75     # 测试报告存放位置
    76     test_report = 'E:ALL_DemoPy_DemoJob3ExamReport'
    77 
    78     discover = unittest.defaultTestLoader.discover(test_dir, 'test_*.py')
    79 
    80     now = time.strftime("%Y-%m-%d_%H_%M_%S_")
    81     filename = test_report + '\' + now + 'result.html'
    82     fp = open(filename, 'wb')
    83     runner = HTMLTestRunner(stream=fp,
    84                             title='测试报告',
    85                             description='用例执行情况:')
    86     runner.run(discover)
    87     fp.close()
    88 
    89     new_report = new_report(test_report)
    90     send_mail(new_report)  # 发送测试报告
    View Code
  • 相关阅读:
    Java实现 蓝桥杯 算法提高 队列操作
    DUILIB创建不规则窗体,自定义控件(很不错的几十篇文章)
    修改窗口属性(全部都是SetWindowLong设置)
    搭建DirectUi开发平台
    _CrtSetBreakAlloc简单内存泄漏检测方法,解决Detected memory leaks!问题
    VLD(Visual LeakDetector)内存泄露库的使用
    设计模式之组合模式
    Moq的使用心得
    Moq 测试 属性,常用方法
    C#中Linq查询基本操作
  • 原文地址:https://www.cnblogs.com/haoabcd2010/p/8585388.html
Copyright © 2020-2023  润新知