user3507825
user3507825

Reputation: 451

How to save created Python win32com msg file without displaying the email in the GUI?

I am using Pywin32 and win32com to programmatically create and save Outlook MSG files. (These are emails that will only ever be saved and never be sent across smtp.) I am able to create and save the emails, but it only works when the display() method is used. This is problematic because it creates and opens the actual Outlook email in the GUI.

When I comment out the display() method, the email message save method just runs forever and yields zero in the debug console and the email is neither created or saved.

The appearance of the Outlook emails in the GUI is not desirable as I will later programmatically create thousands of messages and cannot have them all opening in the GUI. (and having to close them!)

edit: I've done some research here display method and here .net mail class but have not found a way to suppress the GUI display of the email.

How can I create the emails to disk as msg files without them appearing in the Windows GUI as Outlook emails? Code as follows. Thank you.

import sys
import win32com.client as client

MSG_FOLDER_PATH = "d:\\Emails_Msg\\"

html_body = """
<div>
Test email 123
</div><br>
"""

recipient = "[email protected]"
cc = "[email protected]"

outlook = client.Dispatch("outlook.application")

message = outlook.CreateItem(0)
message.To = recipient
message.CC = cc
message.Subject = "foo1"
message.HTMLBody = html_body

# message display method 
message.Display() 

# save the message, only works if message.Display() runs
message_name = MSG_FOLDER_PATH + "foo.msg"
message.SaveAs(message_name)

Upvotes: 0

Views: 1224

Answers (1)

user3507825
user3507825

Reputation: 451

The problem was that Outlook was not opened in the Windows Server. (The simple things at times!) Once it is opened, the display method is no longer needed and emails are written directly to disk.

Upvotes: 0

Related Questions