如何将匹配文件名的电子邮件发送到 Python 中的数据框值?

How can I send emails of matching filenames to dataframe values in Python?

我有兴趣根据以下条件通过 smtplib 包发送电子邮件:-

  1. 电子邮件和文件名在电子表格中。它们如下:-
Name Email
1001 xx@gmail.com   
1002 yy@xxx.com
1003 zz@yyy.com

“名称”列名称应与文件夹中的文件匹配。 2. 主要思想是将文件夹中的文件名与电子表格中的名称进行比较,如果存在匹配项,则将文件夹中的文件发送到匹配的电子邮件地址。 例如,如果文件夹中存在 1001.csv 和 1002.csv,则 1001.csv 将发送到 xx@gmail.com,将 1002.csv 发送到 yy@xxx.com.

import pandas as pd
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# Spreadsheet with emails and  names
email_list = pd.read_excel(r'xxxxx\Email.xlsx')
files1 = glob.glob('Folder_xxx/*.xlsx') #Folder with files to be sent as attachments

# getting the names and the emails
names = email_list['Name']
emails = email_list['Email']
 
for i in range(len(emails)): # iterate through the records
 
    # for every record get the name and the email addresses
    name = names[i]
    email = emails[i]
   
    #Some  help needed from here I believe
    while name == os.path.xxxx:
         smtp_ssl_host = 'smtp.gmail.com'
         smtp_ssl_port = 465
         email_from = "xxx@xxx.com"
         email_pass = "xxxx"
         email_to = email

         filename = (filename)+.csv #Get the filename  matching the name in the while condition. Help on this.
         msg2 = MIMEMultipart()
         msg2['Subject'] = "Present Record(s)"
         msg2['From'] = email_from
         msg2['To'] = email
         fo=open(filename,'rb')
         attach = email.mime.application.MIMEApplication(fo.read(),_subtype="xlsx")
         fo.close()
         attach.add_header('Content-Disposition','attachment',filename=filename)
         msg.attach(attach)
         s2 = smtplib.SMTP_SSL(smtp_ssl_host, smtp_ssl_port)
         s2.login(email_from, email_pass)  
         s2.send_message(msg)
         s2.quit()

如果文件在同一个文件夹中,您可以尝试这样的操作

import os
from collections import ChainMap
folder_path="." # your folder path
my_files=[{each_file.split(".")[0]:each_file} for each_file in os.listdir(folder_path) if each_file.endswith(".csv")]
my_files_dict = dict(ChainMap(*my_files))

然后在你的 for 循环中:

if my_files_dict.get(name):
    print(f"file found:{my_files_dict.get(name)}") # attach this file : my_files_dict.get(name)