'Email gets stuck in outlook outbox when sending via python script

The script can send emails, however if I don't keep outlook open the email gets stuck in outlook 2015 outbox. Even if I have it open it takes 4-5 minutes to finally send. Issue here is that I want it as a scheduled task on a remote desktop, thus I won't be logged in to outlook on the machine. Issue persists w/ or w/o attachments.

import win32com.client
import time
from win32com.client import Dispatch, constants
    
    const=win32com.client.constants
    olMailItem = 0x0
    obj = win32com.client.Dispatch("Outlook.Application")
    newMail = obj.CreateItem(olMailItem)
    newMail.Subject = "subject here"
    newMail.BodyFormat = 2 
    cnt = cnt
    SENDER = "email"
    RECIPIENTS = ["email list"]
    newMail.HTMLBody = """\
    <html>
      <head></head>
      <body>
        <p>There are {cnt} new repricing files uploaded. <br>
           <br>
           ~Sent via Python Code
        </p>
      </body>
    </html>
    """.format(cnt=cnt)
    
    attachment = "file.xlsx"
    newMail.Attachments.Add(attachment)
    newMail.To = "; ".join(RECIPIENTS)
    newMail.display()
    time.sleep(5)
    newMail.Send()

after newMail.send() is called, outlook automatically closes which is nice, but this results in the email getting stuck in outbox.



Solution 1:[1]

You can use Application.Session.SendAndReceive method. Keep in mind that the process is asynchronous. You can use SyncObject.SyncEnd event if you need to wait for the send/receive to finish.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dmitry Streblechenko