• 主页

  • 投资

  • IT

    🔥
  • 设计

  • 销售

关闭

返回栏目

关闭

返回python栏目

76 - 自带库 - smtplib - 发信息

作者:

贺及楼

成为作者

更新日期:2024-10-27 18:05:48

smtplib - 发信息

smtplib库简介

Python 的 smtplib 库用于发送电子邮件。它提供了SMTP(简单邮件传输协议)客户端会话的实现,支持邮件的发送、附件的添加以及与SMTP服务器的交互。smtplib 允许程序自动发送邮件通知、处理邮件列表、实现邮件功能集成等,是自动化邮件处理和通信任务的重要工具。

smtplib库发信息

  1. # -*- coding: utf-8 -*-
  2. import smtplib
  3. from email.mime.text import MIMEText # 引入mail.mime的MIMEText 类来实现支持HTML格式的邮件(email.mime是smtplib模块邮件内容主体的扩展)
  4. class send_email_class():
  5. def __init__(self, msg_from, passwd, server, port):
  6. self.msg_from = msg_from
  7. self.passwd = passwd
  8. self.server = server
  9. self.port = port
  10. def emailpost(self, msg_to, subject, content):
  11. msg = content
  12. msg['Subject'] = subject
  13. msg['From'] = self.msg_from
  14. msg['To'] = msg_to
  15. print(msg)
  16. try:
  17. s = smtplib.SMTP_SSL(self.server, self.port) # 邮件服务器及端口号
  18. s.login(self.msg_from, self.passwd)
  19. s.sendmail(self.msg_from, msg_to, msg.as_string())
  20. print ("发送成功")
  21. except:
  22. print ("发送失败")
  23. finally:
  24. s.quit()
  25. def send_html(self, msg_to, subject, content):
  26. content_html = MIMEText(content)
  27. self.emailpost(msg_to, subject, content_html)
  28. def send_txt_file(self, msg_to, subject, file_name):
  29. data = ""
  30. with open(file_name, 'r') as f:
  31. list1 = f.readlines()
  32. for i in range(0, len(list1)):
  33. list1[i] = list1[i].replace('\n','\r\n') # 普通分行换到邮件分行
  34. data = data+list1[i]
  35. self.emailpost(msg_to, subject, data)
  36. def send_text(self, msg_to, subject, content):
  37. self.emailpost(msg_to, subject, content)
  38. if __name__ == "__main__":
  39. msg_from='XXXXXXXX@qq.com' # 发送方邮箱
  40. passwd='XXXXXXXXXXX' # 填入发送方邮箱的授权码,授权码 - 去邮箱后台开启
  41. server = "smtp.qq.com" # 邮件服务器
  42. port = 465 # port端口号
  43. send_email = send_email_class(msg_from, passwd, server, port)
  44. msg_to='XXXXXXXX@qq.com' # 收件人邮箱
  45. subject="python邮件测试" # 主题
  46. content_html = "<p style='color:#ff00ff'>baidu.com<p>"
  47. # send_email.send_html(msg_to, subject, content_html) # 方法1
  48. # send_email.send_txt_file(msg_to, subject, 'scheduler.txt') # 方法2
  49. content="这是我使用python smtplib及email模块发送的邮件" # 正文
  50. # send_email.send_text(msg_to, subject, content) # 方法3