当前位置 : 主页 > 编程语言 > python >

python 快速发送大量邮件

来源:互联网 收集:自由互联 发布时间:2021-06-25
因为公司需求,需要发送千万封级别邮件。 # coding:utf-8import csvimport smtplibfrom email.mime.text import MIMETextimport threadpoolclass SendMail(): def __init__(self): self.msg = MIMEText(mail_msg, 'html', 'utf-8') self.m

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

# 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'] = "[email protected]"
        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("[email protected]", "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()
上一篇:time模块
下一篇:Django models
网友评论