I'm having a bit of trouble getting to a solution with the following, I created a function that sends emails via Outlook, using the win32 package, cause the smtblib in blocked where I work. The function itself works like a charm:
def sendEmail(emailTo, emailCC, emailSubject, emailAttach, emailBody):
for item in psutil.pids():
if psutil.pid_exists(item):
p = psutil.Process(item)
if p.name() == 'OUTLOOK.EXE':
os.system('taskkill /f /im OUTLOOK.EXE')
break
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.Subject = emailSubject
mail.To = emailTo
mail.CC = emailCC
#mail.Body = emailBody
mail.HTMLBody = emailBody
if not emailAttach:
print('No Attachements...\n')
else:
print('Attaching files...\n')
for i in range(0, len(emailAttach)):
mail.Attachments.Add(emailAttach[i])
mail.Send()
time.sleep(30)
The thing here is, sometimes we need to send multiple different e-mails to different people inside a for loop, however since the code goes faster than the e-mail creation, sometimes it fails, I was wondering if there was a way for me to monitor if the e-mail finished, cause from what I could tell, on the task bar it open a outlook with a gear while it's creating and sending the e-mail. The main point here is if there is a way for me to monitor when the e-mail has been created and indeed sent for me to move on to the next item.
I forced a wait with the 30 seconds sleep but I'm sure there is a better and more pythonic way to do this.
Email submission is inherently asynchronous. Even if a message is successfully sent by Outlook, it is possible the target mailbox no longer exists and you will get back an NDR, sometimes hours later.
If MailItem.Send
did not error out, this is the best you can do.