Search code examples
pythonoutlookwin32com

How to add a member to an existing Outlook Distribution List?


I am trying to add a member to an existing Outlook distribution list using Python library win32com.

I do not have any trouble deleting an existing member with the following code:

import win32com.client

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

myDistributionList = outlook.Folders.Item(1).Folders[5].Items.Item('DL') # Number 5 because the DL is in the contacts folder

firstContact = myDistributionList.GetMember(1)

myDistributionList.RemoveMember(firstContact)

myDistributionList.Save()

Reading VBA documentation, I learnt that to use the method AddMember of a distribution list I must create a recipient object. Even so the following code does not give any error, it seems as it does not run. The DL in Outlook is still empty.

newContact = win32com.client.Dispatch("Outlook.Application").Session.CreateRecipient('[email protected]')

myDistributionList.AddMember(newContact)

myDistributionList.Save()

Solution

  • ANSWER

    Okay, I have solved my own question. I do not know if it is the most efficient way but it runs.

    I had to create two different items. A mail item and a contact item. Then I assigned an address to the contact item and that address was passed to the mail item's property called recipients. Lastly I passed this recipient to the DL.

    myTempItem  = win32com.client.Dispatch("Outlook.Application").CreateItem(0) # Mail item
    
    contact = win32com.client.Dispatch("Outlook.Application").CreateItem(2) # Contact item
    
    contact.Email1Address = '[email protected]'
    
    myTempItem.Recipients.Add(contact.Email1Address)
    
    myDistributionList.AddMembers(myTempItem.Recipients)
    
    myDistributionList.Save()
    
    # And if you want to see the contact group
    myDistributionList.Display()