Home > Net >  How do you use a for loop to send out emails in Python using win32com
How do you use a for loop to send out emails in Python using win32com

Time:11-23

I have a df which has contact details of several people, below is a test example of what it looks like:

first_name    Last_name    email
Steve         Smith        [email protected]
John          Walker       [email protected]
etc...

In short, I want to use Python to send a customised email to each of the people in the df. Here is the code I've used so far:

import win32com.client as win32
import pandas as pd

df = pd.read_excel("test_emails.xlsx")

for i in df.email:
    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.Subject = 'Test email'
    mail.To = i
    mail.HTMLBody = r"""
    Dear recipient,<br><br>
    This is a test email.
    """
    mail.Send()

This works fine, in the sense that it sends the test email to everyone in the email column in the df. However, how could I make the emails more customisable for each recipient? For example, rather than "Dear recipient", to include the first name of each person instead as part of the for loop.

CodePudding user response:

You can iterate through the entire Dataframe row by row and use f-strings to abtain your goal.

import win32com.client as win32
import pandas as pd

df = pd.read_excel("test_emails.xlsx")

for index, row in df.iterrows():
    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.Subject = 'Test email'
    mail.To = row['email']
    mail.HTMLBody = f"""
    Dear {row['first_name']} {row['last_name']},
    This is a test email.
    """
    mail.Send() 
  • Related