环境: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()

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

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

  1. # -*- coding: utf-8 -*-
  2.  
  3. import unittest
  4.  
  5. def sum(a, b):
  6. return a + b
  7.  
  8. def sub(a, b):
  9. return a - b
  10.  
  11. class TestZuoYe(unittest.TestCase):
  12.  
  13. @classmethod
  14. def setUpClass(cls):
  15. print('')
  16.  
  17. @classmethod
  18. def tearDownClass(cls):
  19. print('')
  20.  
  21. def test_Sum(self):
  22. self.assertEqual(4, sum(3, 1))
  23. self.assertNotEqual(8, sum(3, 1))
  24.  
  25. def test_Sub(self):
  26. self.assertEqual(2, sub(3, 1))
  27. self.assertNotEqual(8, sub(3, 1))
  28.  
  29. if __name__ == '__main__':
  30. unittest.main()

然后是发送邮件 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. def send_mail(file_new):
  16.  
  17. msg_from = '' # 发送方邮箱
  18. passwd = '' # 填入发送方邮箱的授权码
  19. msg_to = '' # 收件人邮箱
  20.  
  21. msg_subject = "" # 邮件主题
  22. msg_content = "" # 邮件正文
  23.  
  24. msg = MIMEMultipart()
  25. # 邮件正文是MIMEText:
  26. msg.attach(MIMEText(msg_content, 'plain', 'utf-8'))
  27.  
  28. # # 构造附件,传送当前目录下的 .txt 文件
  29. # att1 = MIMEText(open('mybook.txt', 'rb').read(), 'base64', 'utf-8')
  30. # att1["Content-Type"] = 'application/octet-stream'
  31. # att1["Content-Disposition"] = 'attachment; filename="file1.txt"'
  32. # msg.attach(att1)
  33.  
  34. # 添加附件,发送一个 .html文件
  35. with open(file_new, 'rb') as f:
  36. mime = MIMEBase('html', 'html')
  37. # 加上必要的头信息
  38. mime.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_new))
  39. mime.add_header('Content-ID', '<0>')
  40. mime.add_header('X-Attachment-Id', '')
  41. # 把附件的内容读进来
  42. mime.set_payload(f.read())
  43. # 用Base64编码
  44. encoders.encode_base64(mime)
  45. msg.attach(mime)
  46.  
  47. msg['Subject'] = Header(msg_subject, 'utf-8') # 主题
  48. msg['From'] = msg_from
  49. msg['To'] = msg_to
  50.  
  51. try:
  52. s = smtplib.SMTP_SSL("smtp.qq.com", 465) # 邮件服务器及端口号
  53. s.login(msg_from, passwd)
  54. s.sendmail(msg_from, msg_to, msg.as_string())
  55. print('发送成功!')
  56. except s.SMTPException as e:
  57. print("发送失败!")
  58. finally:
  59. s.quit()
  60.  
  61. # 查找测报告目录,找到最新生成的测试报告文件
  62. def new_report(testreport):
  63. lists = os.listdir(testreport)
  64. lists.sort(key=lambda fn: os.path.getmtime(testreport + "\\" + fn))
  65. file_new = os.path.join(testreport, lists[-1])
  66. print(file_new)
  67. return file_new
  68.  
  69. if __name__ == '__main__':
  70. # 测试用例存放位置
  71. test_dir = 'E:\ALL_Demo\Py_Demo\Job3\ExamCase'
  72. # 测试报告存放位置
  73. test_report = 'E:\ALL_Demo\Py_Demo\Job3\ExamReport'
  74.  
  75. discover = unittest.defaultTestLoader.discover(test_dir, 'test_*.py')
  76.  
  77. now = time.strftime("%Y-%m-%d_%H_%M_%S_")
  78. filename = test_report + '\\' + now + 'result.html'
  79. fp = open(filename, 'wb')
  80. runner = HTMLTestRunner(stream=fp,
  81. title='测试报告',
  82. description='用例执行情况:')
  83. runner.run(discover)
  84. fp.close()
  85.  
  86. new_report = new_report(test_report)
  87. send_mail(new_report) # 发送测试报告

python3使用SMTP发送邮件的更多相关文章

  1. 【Python3】SMTP发送邮件

    犹豫和反复浪费了大量时间. 与朋友言 在完成一个邮件发送程序之前我根本不明白什么是邮件,哪怕已经读过廖雪峰大神的文章,没有贬低大神的意思,大神的博客已经非常的详细, 是我的眼大肚皮小毛病在作祟,由一个 ...

  2. php用smtp发送邮件

    php用smtp发送邮件 1.其实用smtp协议发送邮件很简单,用框架或者原生都可以,我们需要用到class.phpmailer.php 和class.smtp.php,大家可以去网上下载. 这是一个 ...

  3. phpmailer,smtp发送邮件实例(转)

    一,用phpmailer发送邮件 查看复制打印? <?php   include "class.phpmailer.php";    //包函邮件发送类      //邮件发 ...

  4. python通过SMTP发送邮件失败,报错505/535

    python通过SMTP发送邮件失败:错误1:smtplib.SMTPAuthenticationError: (550, b'User has no permission')    我们使用pyth ...

  5. linux 下 用phpmailer类smtp发送邮件始终不成功,提示:ERROR: Failed to co

    https://zhidao.baidu.com/question/509191264.html?fr=iks&word=PHPMailerSMTP+connect()+failed& ...

  6. python大法好——Python SMTP发送邮件

    Python SMTP发送邮件 SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式. py ...

  7. 运维监控-Zabbix Server 使用QQ SMTP发送邮件报警及定制报警内容

    运维监控-Zabbix Server 使用QQ SMTP发送邮件报警及定制报警内容 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 本篇博客采用腾讯邮箱,想必大家都对QQ很了解,所以 ...

  8. gitlab配置通过smtp发送邮件(QQ exmail腾讯企业为例)

    gitlab配置通过smtp发送邮件(QQ exmail腾讯企业为例) 首先祭出官网文档链接:https://docs.gitlab.com/omnibus/settings/smtp.html 其实 ...

  9. PHP 通过带SSL的SMTP 发送邮件的处理

    客户端与SMTP服务器的通讯, 是通过固定的命令以及返回编号完成的. 发送Email, 需要经过的步骤有创建socket (区分带ssl, 还是不带ssl)执行命令, 并检查返回值是否与预期一致, 不 ...

随机推荐

  1. hibernate hql 语句中 in 的用法

    例子描述查询一些班级中的学生 /** * * @param city * @return */ public List<Student> studentList(final Integer ...

  2. 小米6安装google play

    http://bbs.xiaomi.cn/t-13579116 http://m.mk52.cn/jiaocheng/3288.html 步骤: 1.下载需要的文件并解压 (http://techta ...

  3. [转]2年SQL Server DBA调优方面总结

      2年SQL Server DBA调优方面总结 当2年dba 我觉得,有些东西需要和大家分享探讨,先书单. 书单 1.<深入解析SQL Server 2008 系列> 这个就是mssql ...

  4. Drawing-Order-Of-meshes-and-sprites

    Sprite 和 Mesh Render 共存 [CanEditMultipleObjects] [CustomEditor(typeof(MeshRenderer))] public class M ...

  5. iOS tableView下拉图片放大

    事实上这个效果,本质上就是在你tableView下拉 造成offset时候. 保持你顶部图片的y坐标点还停留在下拉时屏幕的顶点(offset), 而图片的长度变为原始的height长度-(offset ...

  6. Android-RelativeLayout布局技巧(一)

    如果有一个需求是这样的,在标题中的右上角有一个button <?xml version="1.0" encoding="utf-8"?> <L ...

  7. js - 模块化开发的兼容exports的套路

    补充:除了第一种的套路,还可以这样使用第二种.都是用来自执行函数的.第二种的好处是,还可以返回一个true. // 常用 ;(function () {})(); // 小技巧(如果不加上!会报错,加 ...

  8. 1.const

    在C++中,const 的含义并没有改变,只是对细节进行了一些调整,以下是最主要的两点. 一.C++中的 const 更像编译阶段的 #define 先来看下面的两条语句: ; int n = m; ...

  9. 680. Valid Palindrome II【easy】

    680. Valid Palindrome II[easy] Given a non-empty string s, you may delete at most one character. Jud ...

  10. Masonry介绍与使用实践:快速上手Autolayout【转载】

    MagicNumber -> autoresizingMask -> autolayout 以上是纯手写代码所经历的关于页面布局的三个时期 在iphone1-iphone3gs时代 win ...