#-*- coding: utf-8 -*- # python2 import os import time import random import smtplib from time import strftime from email import encoders from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr, formataddr from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase img_list = os.listdir(‘/home/wy/Desktop/xx‘) # img_list = os.listdir(‘/home/whucs/wangyong/xx‘) def _format_addr(s): name, addr = parseaddr(s) return formataddr(( Header(name, ‘utf-8‘).encode(), addr.encode(‘utf-8‘) if isinstance(addr, unicode) else addr)) def SendSSLEmail(to_list): # from_addr = "[email protected]" #发件人 # pwd = "tvsbkyufaeyceaeb" #密码 # to_addr = "@qq.com" #收件人 # smtp_server = "smtp.qq.com" from_addr = "xxxxxx@126.com" #发件人 pwd = "xxxxxxxxx" #密码 # # to_addr = "@qq.com" #收件人 smtp_server = "smtp.126.com" msg = MIMEMultipart() msg[‘From‘] = _format_addr(u‘meizi.jiandan <%s>‘ % from_addr) # msg[‘To‘] = _format_addr(u‘doggy <%s>‘ % to_addr) msg[‘To‘] = ";".join(to_list) title = time.strftime("%Y-%m-%d",time.localtime()) + ‘ 煎蛋妹子图‘ msg[‘Subject‘] = Header(title, ‘utf-8‘).encode() # msg.attach(MIMEText(‘手机常年静音,接电话全靠缘分‘, ‘html‘, ‘utf-8‘)) for i in range(10): # 添加附件就是加上一个MIMEBase,从本地读取一个图片: img = random.choice(img_list) with open(‘xx/‘+img, ‘rb‘) as f: # 设置附件的MIME和文件名,这里是png类型: mime = MIMEBase(‘image‘, ‘jpg‘, filename=img) # 加上必要的头信息: mime.add_header(‘Content-Disposition‘, ‘attachment‘, filename=img) mime.add_header(‘Content-ID‘, ‘<0>‘) mime.add_header(‘X-Attachment-Id‘, ‘0‘) # 把附件的内容读进来: mime.set_payload(f.read()) # 用Base64编码: encoders.encode_base64(mime) # 添加到MIMEMultipart: msg.attach(mime) # msg.attach(MIMEText(‘<html><body><h1>Hello</h1><p><img src="cid:‘ + str(i) + ‘"></p></body></html>‘, ‘html‘, ‘utf-8‘)) server = smtplib.SMTP_SSL(smtp_server, 465) server.set_debuglevel(1) server.login(from_addr, pwd) server.sendmail(from_addr, to_list, msg.as_string()) # 一次可以发多人,list server.quit() if __name__ == ‘__main__‘: mailto_list = ["[email protected]"] # mailto_list = ["[email protected]","[email protected]","[email protected]","[email protected]"] SendSSLEmail(mailto_list)
时间: 2024-10-19 19:12:39