由於公司需求,須要發送千萬封級別郵件。html
# coding:utf-8 import csv import smtplib from email.mime.text import MIMEText import threadpool class SendMail(): def __init__(self): self.msg = MIMEText(mail_msg, 'html', 'utf-8') self.msg['Subject'] = mailSubject # 發件人信息 self.msg['From'] = "FreeFire@garena.com" self.login() def run(self, user): res = self.send(user) if not res: self.s.login() self.send(user) def login(self): ''' 登陸smtp server,這裏須要手動修改 ''' self.s = smtplib.SMTP('smtp.qq.com', 465, timeout=30) self.s.login("xxx@qq.com", "password") def send(self, user): try: self.msg['To'] = user self.s.sendmail(self.msg['From'], self.msg['To'], self.msg.as_string()) f.write("{} 發送成功\n".format(user)) print("{} 發送成功".format(user)) return True except Exception as e: print("{} 發送失敗".format(user)) f.write("{} 發送失敗\n".format(user)) import traceback traceback.print_exc() return False def __del__(self): self.s.close() def sm(user): SendMail().run(user) if __name__ == '__main__': with open('test.html', 'r+') as f: mail_msg = f.read() mailSubject = "the is test mail" # 發送日誌 f = open('send.log', 'a+') # 發送郵件列表 mails = [] # mails_path: 一個csv文件,裏面是全部的mail信息 mails_path = "test-users.txt" with open(mails_path, newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: mails.append(row['email']) pool = threadpool.ThreadPool(2) requests = threadpool.makeRequests(sm, mails) [pool.putRequest(req) for req in requests] pool.wait() f.close()