Adding existing contacts to outlook distribution list in Python

304 Views Asked by At

I want to use python to add contacts to an existing distribution list (DL). I am using below code which stores the member's email address of the DL to an array. I am able to achieve this by the below code.

import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
address_lists = outlook.AddressLists
dls = address_lists['Global Address List']
contact = win32com.client.Dispatch("Outlook.Application").CreateItem(2)

contacts = dls.AddressEntries.Item('DL Data').Members
group_mail_list = []

for c in contacts:
    # print(c)
    group_mail_list.append(c.GetExchangeUser().PrimarySmtpAddress.lower())
group_mail_list

I am not sure how to add contact to the DL. For example, I want to add the contact '[email protected]' which already exists in the address book but this contact is not a member of the 'DL Data'. How can I achieve this?

Thanks for your help

1

There are 1 best solutions below

2
Dmitry Streblechenko On

Can't easily do that using Outlook Object Model - DistListItem only exposes AddMember/AddMembers methods, which take a Recipient or Recipients objects respectively. This means you can only pass Recipients collection from an existing message (MailItem.Recipients) or from an address book dialog (SelectNamesDialog.Recipients collection). You can also create a temporary recipient using Namespace.CreateRecipient and then resolve it (Recipient.Resolve), but that means Outlook should be able to resolve the name passed to Namespace.CreateRecipient - the entry must be visible to the address book and it should be unique (recipient won't be resolved if the name ambiguous).

If using Redemption (I am its author) is an option, it exposes RDODistListItem.AddContact method, which can take either a contact or another distribution list.