Reputation: 89
I'm trying to send multiple e-mails with different file attachments in each one.
Like this: file_A go to [email protected] file_B go to [email protected] ...
I tried this code, but when I'm looping though the dictionary all of my e-mails goes to [email protected], instead of A to A, B to B, C to C as intended.
import pandas as pd
import shutil, os
import os
import tempfile
import win32com.client as win32
import glob, os
npath="yourpath/"
files=['file_a.xlsx','file_b.xlsx','file_c.xlsx']
mails=dict(zip(['[email protected]','[email protected]','[email protected]'],files))
for file in os.listdir(npath):
if file.endswith(".xlsx"):
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
for id,i in mails.items():
mail.To = id
mail.Subject = 'Test'
mail.HtmlBody = 'testing'
mail.Attachments.Add(os.path.join(npath,file))
mail.Display()
I'm pretty sure my problem is this loop or my dictionary, but after trying for hours couldn't solve by my self.
for id,i in mails.items():
print(id)
mail.To = id
Upvotes: 0
Views: 253
Reputation: 5590
Your code should use mails
dict to iterate over the list of files, here is an example:
files=['file_a.xlsx','file_b.xlsx','file_c.xlsx']
mails=dict(zip(['[email protected]','[email protected]','[email protected]'],files))
for mail_id, file in mails.items():
if file.endswith(".xlsx"):
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = mail_id
mail.Subject = 'Test'
mail.HtmlBody = 'testing'
mail.Attachments.Add(os.path.join(npath,file))
mail.Display()
If you need to use exatcly your method, you have to add a file match check in the second loop:
for mail_id, file_name in mails.items():
if file.endswith(file_name):
mail.To = id
break
Note: i didn't use id
as variable name because it's a reserved builtin python function
Upvotes: 1
Reputation: 3093
Your loop returns correct order of id. The dictionary also contains correct key value pair. Your for loop ends at mail_c and hence getting selected for all files.
You can fix it by bringing the mailing content/logic inside for loop
for file in os.listdir(npath):
if file.endswith(".xlsx"):
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
for id,i in mails.items():
mail.To = id
mail.Subject = 'Test'
mail.HtmlBody = 'testing'
mail.Attachments.Add(os.path.join(npath,file))
mail.Display()
Upvotes: 0