I want to write a python script that checks a column value in excel sheet and sends mail to that particular person in outlook by the name of distribution list(DL). I am unable to fetch DL with the following code. Please help me on this.
More details: The sender should be the DL name i.e., DL IQWDL SSDBU NEC Global [email protected] The receiver should an individual name i.e., [email protected]
Code:
import win32com.client as win32
import pandas as pd
#Read the excel file
xl = pd.read_excel('C:\\Users\\rahulk\\Downloads\\corepy\\excel_report.xlsx')
#Select the email addresses from a specific column in the Excel file
email_addresses = xl['Email'].tolist()
#Connect to Outlook and get the distribution list your text
outlook = win32.gencache.EnsureDispatch("Outlook.Application")
dl = outlook.Session.GetDefaultFolder(win32.constants.olFolderContacts).GetDistributionListFromID("[email protected]")
#Loop through the email addresses and send the email your text
for email_address in email_addresses:
email = outlook.CreateItem(win32.constants.olMailItem)
email.To = email_address
email.Subject = "Email Subject"
email.Body = "Email Body"
email.SentOnBehalfOfName = dl.DLName
email.Send()
#Release the Outlook instance
outlook = None
The Outlook object model doesn't provide the
GetDistributionListFromIDmethod for theFolderclass. To find an item in the folder you need to use theFind/FindNextorRestrictmethods of the Items class. Read more about these methods in the articles I wrote for the technical blog:Be aware, the
Toproperty expects a semicolon-delimited string list of display names for theTorecipients for the Outlook item. Otherwise, I'd suggest using theRecipeints.Addmethod for adding recipients. See How To: Fill TO,CC and BCC fields in Outlook programmatically for more information.