-1
我的任務是發送大約250封電子郵件,每封電子郵件大約30kb附件。每個附件對收件人都是唯一的。我的下面的代碼工作,雖然我覺得它太慢了,它每7秒發送一封電子郵件,其中250封電子郵件將花費29分鐘。顯然,將它並行將有助於移動,但我很好奇我的代碼是否可以改進。請注意,我還沒有實施目標附件和電子郵件,因爲這不應該造成如此大的性能影響。Python - 發送大量電子郵件
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次?似乎每個循環都沒有實現任何不同。 –
Hi @PeterWood,如上所述,我還沒有針對附件和電子郵件,因爲它不應該在性能上產生太大的差異。我可以在稍後插入它們。最初,我想要發送電子郵件時表現出色,然後我將參數化腳本 – Krishn