
Python 的 smtplib 库用于发送电子邮件。它提供了SMTP(简单邮件传输协议)客户端会话的实现,支持邮件的发送、附件的添加以及与SMTP服务器的交互。smtplib 允许程序自动发送邮件通知、处理邮件列表、实现邮件功能集成等,是自动化邮件处理和通信任务的重要工具。
# -*- coding: utf-8 -*-import smtplibfrom email.mime.text import MIMEText # 引入mail.mime的MIMEText 类来实现支持HTML格式的邮件(email.mime是smtplib模块邮件内容主体的扩展)class send_email_class():def __init__(self, msg_from, passwd, server, port):self.msg_from = msg_fromself.passwd = passwdself.server = serverself.port = portdef emailpost(self, msg_to, subject, content):msg = contentmsg['Subject'] = subjectmsg['From'] = self.msg_frommsg['To'] = msg_toprint(msg)try:s = smtplib.SMTP_SSL(self.server, self.port) # 邮件服务器及端口号s.login(self.msg_from, self.passwd)s.sendmail(self.msg_from, msg_to, msg.as_string())print ("发送成功")except:print ("发送失败")finally:s.quit()def send_html(self, msg_to, subject, content):content_html = MIMEText(content)self.emailpost(msg_to, subject, content_html)def send_txt_file(self, msg_to, subject, file_name):data = ""with open(file_name, 'r') as f:list1 = f.readlines()for i in range(0, len(list1)):list1[i] = list1[i].replace('\n','\r\n') # 普通分行换到邮件分行data = data+list1[i]self.emailpost(msg_to, subject, data)def send_text(self, msg_to, subject, content):self.emailpost(msg_to, subject, content)if __name__ == "__main__":msg_from='XXXXXXXX@qq.com' # 发送方邮箱passwd='XXXXXXXXXXX' # 填入发送方邮箱的授权码,授权码 - 去邮箱后台开启server = "smtp.qq.com" # 邮件服务器port = 465 # port端口号send_email = send_email_class(msg_from, passwd, server, port)msg_to='XXXXXXXX@qq.com' # 收件人邮箱subject="python邮件测试" # 主题content_html = "<p style='color:#ff00ff'>baidu.com<p>"# send_email.send_html(msg_to, subject, content_html) # 方法1# send_email.send_txt_file(msg_to, subject, 'scheduler.txt') # 方法2content="这是我使用python smtplib及email模块发送的邮件" # 正文# send_email.send_text(msg_to, subject, content) # 方法3