Search code examples
pythonemailoutlookwin32com

Sending Outlook mail to multiple distribution lists in Python


I'm using Python and win32com.client to send Outlook mails to multiple distribution lists like so:

olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = "This is subject"
newMail.To = "[email protected]"
newMail.CC = "samplegrp1; samplegrp2"   # offending statement
//some html processing in mail content
newMail.Send()

The above code works as I'm able to send to a single group using:

newMail.CC = "samplegrp1"

but when I try to send to multiple groups (the offending statement above), I receive the following error:

>     return self._oleobj_.InvokeTypes(61557, LCID, 1, (24, 0), (),)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Out
look', 'Outlook does not recognize one or more names. ', None, 0, -2147467259),
None)

I tried using comma instead of semicolon, using + operator, etc. but to no avail.

If anyone can help, thanks.


Solution

  • Try this:

    from win32com.client.gencache import EnsureDispatch
    from win32com.client import constants
    
    outlook = EnsureDispatch("Outlook.Application")
    newMail = outlook.CreateItem(constants.olMailItem)
    newMail.Subject = "This is subject"
    
    samplegrp1 = newMail.Recipients.Add("samplegrp1")
    samplegrp2 = newMail.Recipients.Add("samplegrp2")
    samplegrp1.Type = constants.olCC
    samplegrp3.Type = constants.olCC
    newMail.Recipients.ResolveAll()
    

    This is documented on How to: Specify Different Recipient Types for a Mail Item.