I'm trying to use an Excel sheet to populate an Outlook email draft and have every new row create a new email. I'm trying to achieve this using the openpyxl library. The Excel file looks something like this. Excel Example
I've tried to iterate over each row using list comprehension but the results are pretty much the same, I get one email created with the first row of data and but the rest of the information is not used. The only way I can use the information now is to change the row_offset number by myself, but obviously that doesn't work for doing many rows.
def get_info():
loc = "Excel_file_location.xlsx"
wb = load_workbook(loc)
info = []
ws = wb[wb.sheetnames[0]]
ws = wb.active
for row in ws.iter_rows(row_offset=1):
for cell in row:
info.append(str(cell.value))
return info
data = get_info()
text = "Hello, {1}! Work order #{0} is complete".format(data[0], data 1 )
def Emailer(text1, subject, recipient): import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = recipient
mail.Subject = subject
mail.HtmlBody = text1
mail.Display(False)
Afterwards I would call on the Emailer function using something like
Emailer(text, "Completed WO {0} | {1}".format(data[0], data 1 ), data[2])
But I'm stumped on how to make this function work separately for every row of an Excel sheet. As of now it will only keep doing writing the same email over and over again without reading the rest of the rows.
My suggestion would be to wrap every row into an object, and push the objects into the list info
like so:
class Recipient():
def __init__(self, w_order, name, email):
self.w_order = w_order
self.name = name
self.email = email
def get_info():
loc = "Excel_file_location.xlsx"
wb = load_workbook(loc)
info = []
ws = wb[wb.sheetnames[0]]
ws = wb.active
for row in range(2, 5):
rec = Recipient("", "", "")
for col in range(ord('A'), ord('D')):
if chr(col) == 'A':
rec.w_order = ws[chr(col) + str(row)].value
elif chr(col) == 'B':
rec.name = ws[chr(col) + str(row)].value
elif chr(col) == 'C':
rec.email = ws[chr(col) + str(row)].value
info.append(rec)
return info
From there on you could access the information from get_info()
in your mail function in a loop like so:
def Emailer(text1, subject, recipient):
import win32com.client as win3
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = recipient
mail.Subject = subject
mail.HtmlBody = text1
mail.Display(False)
data = get_info()
for i in range(0, len(data)):
Emailer(text, "Completed WO {0} | {1}".format(data[i].w_order, data[i].name), data[i].email)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.