1 import smtplib,os 2 from email.mime.text import MIMEText 3 from email.mime.multipart import MIMEMultipart 4 import base64 5 class SendMail(object): 6 def __init__(self,username,passwd,recv,title,content, 7 file=None,ssl=True, 8 email_host= 'smtp.qq.com',port=25,ssl_port=465): 9 '''10 :param username: 用户名11 :param passwd: 密码12 :param recv: 收件人,多个要传list ['a@qq.com','b@qq.com]13 :param title: 邮件标题14 :param content: 邮件正文15 :param file: 附件路径,如果不在当前目录下,要写绝对路径,默认没有附件16 :param ssl: 是否安全链接,默认为普通17 :param email_host: smtp服务器地址,默认为163服务器18 :param port: 非安全链接端口,默认为2519 :param ssl_port: 安全链接端口,默认为46520 '''21 self.username = username # 用户名22 self.passwd = passwd # 密码23 self.recv = recv # 收件人,多个要传list ['a@qq.com','b@qq.com]24 self.title = title # 邮件标题25 self.content = content # 邮件正文26 self.file = file # 附件路径,如果不在当前目录下,要写绝对路径27 self.email_host = email_host # smtp服务器地址28 self.port = port # 普通端口29 self.ssl = ssl # 是否安全链接30 self.ssl_port = ssl_port # 安全链接端口31 32 def send_mail(self):33 msg = MIMEMultipart() #定义内嵌资源的邮件体34 #发送内容的对象35 if self.file:#处理附件的36 file_name = os.path.split(self.file)[-1]#只取文件名,不取路径37 try:38 f = open(self.file, 'rb').read()39 except Exception as e:40 raise Exception('附件打不开!!!!')41 else:42 att = MIMEText(f,"base64", "utf-8")43 att["Content-Type"] = 'application/octet-stream'44 new_file_name='=?utf-8?b?' + base64.b64encode(file_name.encode()).decode() + '?='45 #这里是处理文件名为中文名的,必须这么写46 att["Content-Disposition"] = 'attachment; filename="%s"'%(new_file_name)47 msg.attach(att)48 msg.attach(MIMEText(self.content))#邮件正文的内容49 msg['Subject'] = self.title # 邮件主题50 msg['From'] = self.username # 发送者账号51 msg['To'] = ','.join(self.recv) # 接收者账号列表52 53 54 html = """\55 上午好!56 祝愿春节快乐57 试下发个测试连接 连接地址58 """59 part2 = MIMEText(html, 'html')60 msg.attach(part2)61 62 63 if self.ssl:64 self.smtp = smtplib.SMTP_SSL(self.email_host,port=self.ssl_port)65 else:66 self.smtp = smtplib.SMTP(self.email_host,port=self.port)67 68 #发送邮件服务器的对象69 self.smtp.login(self.username,self.passwd)70 71 try:72 self.smtp.sendmail(self.username,self.recv,msg.as_string())73 except Exception as e:74 print('出错了。。',e)75 else:76 print('发送成功!')77 self.smtp.quit()78 79 80 if __name__ == '__main__':81 m = SendMail(82 username='XXX@qq.com',83 passwd='发短信获取',84 recv=['xxx@qq.com'],85 title='louis email test',86 content='',87 file=r'C:\Users\BJQT\Desktop\test.jpg'88 )89 m.send_mail()