Python - 发送批量电子邮件

时间:2017-05-06 20:59:50

标签: python python-3.x email smtplib

我的任务是发送大约250封电子邮件,每封电子邮件附件大约30kb。每个附件对于收件人都是唯一的。我的下面的代码工作,虽然我觉得它太慢,它每7秒发送一封电子邮件,250封电子邮件需要29分钟。显然,将它并行化将有助于移动事物,我很好奇我的代码是否可以改进。请注意,我尚未实施目标附件和电子邮件,因为这不会导致如此大的性能损失。

import os,datetime
def send_mail(recipient, subject, message, files=None):

    import smtplib,email,os
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.application import MIMEApplication
    from os.path import basename

    username = "myemail"
    password ="mypass"

    mailServer = smtplib.SMTP('smtp-mail.outlook.com', 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(username, password)

    for i in range(1,15):
        try:
            msg = MIMEMultipart()
            msg['From'] = username
            msg['To'] = recipient
            msg['Subject'] = subject
            msg.attach(MIMEText(message))
            for f in files or []:
                with open(f, "rb") as fil:
                    part = MIMEApplication(
                        fil.read(),
                        Name=basename(f)
                    )
                    part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
                    msg.attach(part)


            print('sending mail to ' + recipient + ' on ' + subject)


            mailServer.sendmail(username, recipient, msg.as_string())


        except error as e:
            print(str(e))

    mailServer.close()

print(datetime.datetime.now())
send_mail('recipent, 'Sent using Python', 'May the force be with you.',["colours.xls"])
print(datetime.datetime.now())

1 个答案:

答案 0 :(得分:-1)

您应该对代码进行分析,以查看大部分时间消耗的内容。 我建议使用cProfile + snakeviz

python -m cProfile -o program.prof my_program.py
snakeviz program.prof