【问题标题】:Python - send bulk emailsPython - 发送批量电子邮件
【发布时间】:2017-05-06 20:59:49
【问题描述】:

我的任务是发送大约 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())

【问题讨论】:

  • 为什么会循环14次?每个循环似乎没有什么不同。
  • 嗨@PeterWood,如上所述,我还没有针对附件和电子邮件,因为它不应该对性能产生太大影响。我可以稍后将它们插入。最初,我想要在发送电子邮件时表现良好的东西,然后我将参数化脚本

标签: python python-3.x email smtplib


【解决方案1】:

您应该分析您的代码以查看最耗时的代码。 我建议使用cProfile + snakeviz

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    • 2014-08-19
    • 2018-09-29
    • 2016-04-04
    • 2010-12-11
    • 2016-03-25
    相关资源
    最近更新 更多