import smtplib
import traceback
from email.mime.text import MIMEText
from config.config import * #config.config为配置文件,文件内容有smtp_host ,smtp_from_email ,smtp_pwd ,smtp_port 几个参数
class EmailSender(object):
def __init__(self):
self.smtp_host=smtp_host #发送邮件的smtp服务器(QQ邮箱:"smtp.qq.com",163邮箱:"smtp.163.com")
self.smtp_from_email=smtp_from_email #邮件发送者的邮箱
self.smtp_pwd=smtp_pwd #邮件发送者的邮箱的授权码
self.smtp_port=smtp_port #smtp邮箱的端口,默认是465
def send_email(self,to_email_list,subject,body):
'''
发送邮件
param to_email_list: 收件人邮箱列表,格式["123@qq.com","123@163.com"]
param subject: 邮件主题,格式:"邮件主题"
param body: 邮件内容, 格式:"邮件所说的内容"
'''
msg=MIMEText(body,'plain','utf-8') #把内容转换成指定格式;邮箱内容,格式,编码
msg["From"]=self.smtp_from_email #发件人
msg["To"]=",".join(to_email_list) #收件人列表,转换成string类型,使用逗号隔开
msg["Subject"]=subject #邮件标题
try:
SmtpSslClient=smtplib.SMTP_SSL(self.smtp_host,self.smtp_port) #实例化一个SMTP_SSL对象
Loginer=SmtpSslClient.login(self.smtp_from_email,self.smtp_pwd) #登录smtp服务器
print("登录结果:Loginer=",Loginer) #loginRes = (235, b'Authentication successful')
if Loginer[0]==235:
print("登录成功,code=",Loginer[0])
SmtpSslClient.sendmail(self.smtp_from_email,to_email_list,msg.as_string()) #发件人,收件人列表,邮件内容
print("mail has been send successfully,message:",msg.as_string())
SmtpSslClient.quit() #退出邮箱
else:
print("邮件登录失败,发送失败。code=",Loginer[0],"message=",msg.as_string())
except Exception as e:
traceback.print_exc() #打印堆栈报错信息
print("邮件发送失败,报错信息:",e)
if __name__=="__main__":
senders=EmailSender()
senders.send_email(["123456@qq.com","123456@163.com"],"测试邮件发送的标题","这是一个测试邮件发送的内容")
参考博客:https://blog.csdn.net/qq_27648991/article/details/82898775