-1

I've been tasked with sending around 250 emails with around 30kb attachments per email. Each attachment is unique to the recipient. My below code works, although I feel it's too slow, it sends an email around every 7 seconds which across 250 emails will take 29 mins. Obviously parallelising it would help move things along however, I'm curious as to whether my code can be improved. Please note that I haven't yet implemented the targeted attachment and emails as that shouldn't cause such a large performance hit.

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())
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
Krishn
  • 813
  • 3
  • 14
  • 28
  • 1
    Why does it loop 14 times? It doesn't seem to achieve anything different with each loop. – Peter Wood May 06 '17 at 21:24
  • Hi @PeterWood , as stated above, I've not targeted attachment and emails just yet as it shouldn't make too much of a difference in performance. I can plug them in later. Initially, I want something which performs well in sending out emails, then I'll parameterize the script – Krishn May 06 '17 at 21:32

1 Answers1

-1

You should profile your code to see what is consuming the most of time. I would recommend using cProfile + snakeviz.

python -m cProfile -o program.prof my_program.py
snakeviz program.prof
matusko
  • 3,487
  • 3
  • 20
  • 31