python 快速发送大量邮件

时间:2019-10-23
本文章向大家介绍python 快速发送大量邮件,主要包括python 快速发送大量邮件使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

因为公司需求,需要发送千万封级别邮件。

# 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()

原文地址:https://www.cnblogs.com/GXLo/p/11725243.html