P37 - Python发送带附件的邮件 - 图1 P37 - Python发送带附件的邮件 - 图2 P37 - Python发送带附件的邮件 - 图3 P37 - Python发送带附件的邮件 - 图4

你好,我是UP:法学院毕业的Python程序员兆锋(点击查看🏆近期的付费答疑记录)
如有学习问题,欢迎加入学习群和我交流❤交流群

下面是本讲课程的视频、代码和配套文档:

主要内容

视频内容

点击下方链接,直达本讲视频
点击查看【bilibili】

本讲代码

  1. # -*- coding: utf-8 -*-
  2. # @Time : 2020/8/23 2:22
  3. # @公众号 :Python自动化办公社区
  4. # @File : 24_用Python发送带附件的邮件.py
  5. # @Software: PyCharm
  6. # @Description:
  7. # -*- coding: utf-8 -*-
  8. # @Time : 2020/8/23 2:15
  9. # @公众号 :Python自动化办公社区
  10. # @File : 23_用Python发送普通的文字邮件.py
  11. # @Software: PyCharm
  12. # @Description:
  13. import smtplib
  14. from smtplib import SMTP_SSL
  15. from email.mime.text import MIMEText
  16. from email.mime.multipart import MIMEMultipart
  17. from email.mime.application import MIMEApplication
  18. from email.header import Header
  19. host_server = 'smtp.sina.com'
  20. sender_sina = 'your_email@sina.com'
  21. pwd = 'your_pwd'
  22. sender_sina_mail = 'your_email@sina.com'
  23. receiver = 'others_email@sina.com'
  24. mail_title = '这是标题'
  25. mail_content = '这是正文'
  26. msg = MIMEMultipart()
  27. msg['Subject'] = Header(mail_title, 'utf-8')
  28. msg['From'] = sender_sina_mail
  29. msg['To'] = Header('mail_title', 'utf-8')
  30. msg.attach(MIMEText(mail_content, 'html', 'utf-8'))
  31. # 添加附件
  32. attachment = MIMEApplication(open('student.xls', 'rb').read())
  33. attachment.add_header('Content-Disposition', 'attachment', filename='student.xls')
  34. msg.attach(attachment)
  35. try:
  36. smtp = SMTP_SSL(host_server)
  37. smtp.set_debuglevel(1)
  38. smtp.ehlo(host_server)
  39. smtp.login(sender_sina, pwd)
  40. smtp.sendmail(sender_sina_mail, receiver, msg.as_string())
  41. smtp.quit()
  42. print('success')
  43. except smtplib.SMTPException:
  44. print('error')

配套文档

student.xls

拓展内容

提问与答疑

提供以下3种交流方式:

  • 有任何问题,请加入Python学习群,和我交流~❤交流群
  • 也期待加我好友,我们深入沟通,我的微信:hdylw1024,请务必注明来意,否则很难通过。
  • 或者你也可以直接在本文档的留言板留言,和大家一起讨论~