'Create a pst file with a bunch of msg files using win32com python

I have a bunch of msg files in a directory, I'd like to kinda put/zip them in a pst file. I've seen some solutions like Aspos Email which needs JVM on the machine. I want to do it with Outlook itself using win32com.client. Please post if there is a way to do it. Thanks



Solution 1:[1]

In Outlook Object Model, call Namespace.AddStore (or AddStoreEx) to add a new PST file, find the store in the Namespace.Stores collection (AddStore does not return the newly added store), call Store.GetRootFolder() to get the top level folder and add folders and items. Keep in mind that OOM code cannot run in a service, and that you need to log to an existing profile in Outlook first (Namespace.Logon).

If using Redemption (I am its author) is an option (it can run in a service and does not require to log to an existing profile first), but can create a PST file as well as create folders and messages there. In VB script:

set Session = CreateObject("Redemption.RDOSession")
set pstStore = Session.LogonPstStore("c:\temp\test.pst", 1, "Test PST Store" )
set RootFolder = pstStore.IPMRootFolder
set newFolder = RootFolder.Folders.OpenOrAdd("Test folder")
set newItem = newFolder.Items.Add("IPM.Note")

newItem.Sent = true
newItem.Subject = "test"
newItem.HTMLBody = "test <b>bold</b> text"
newItem.Recipients.AddEx "The user", "[email protected]", "SMTP", olTo
vSenderEntryId = Session.AddressBook.CreateOneOffEntryID("Joe The Sender", "SMTP", "[email protected]", false, true)
set vSender = Session.AddressBook.GetAddressEntryFromID(vSenderEntryId)
newItem.Sender = vSender
newItem.SentOnBehalfOf = vSender
newItem.SentOn = Now
newItem.ReceivedTime = Now
newItem.Save

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