我有一個 smtplib 函式,它回圈遍歷 2 個 excel 檔案,然后打開它們并將它們添加為附件。現在有通用名稱,但我認為從資料中獲取資訊并將其用作檔案的名稱會很酷。例如,如果我已被用戶過濾,我想根據資料框中的“位置”列來獲取他們的位置。
目標:將當前名為“File1.xlsx”和“File2.xlsx”的 2 個檔案重命名為“location_email_reminder1_3-4-2022”和“location_email_reminder2_3-4-2022”
到目前為止,這是我的代碼:
#imports
import datetime as dt
from datetime import date
import smtplib
import pandas as pd
from email.message import EmailMessage
#data
today = date.today()
today_clean = today.strftime("%m-%d-%Y")
#these are saved to my computer
files = ['file1.xlsx', 'file2.xlsx']
#real code- location is a string that comes from a dataframe
location = df.loc[df['Login Key'] == email, 'Location Name'][0]
#test code for stackoverflow
location = 'USA'
#for renaming the file, these arent real files, only names
new_attach = [f"{location}_email_reminder1_{today_clean}.xlsx",f"{territory}_email_reminder2_{today_clean}.xlsx"]
#loop for the file names
msg = EmailMessage()
for filename in files:
with open(filename, 'rb') as file:
file_data = file.read()
msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file.name)
通常,如果它是一個檔案,我可以使用“檔案名”方法更改名稱,但我不確定如何為超過 1 個檔案執行此操作。
uj5u.com熱心網友回復:
您可以使用該函式創建一個字典,zip并將舊名稱作為鍵來將所需的新名稱傳遞給filename引數。
...
new_attach = [f"{location}_email_reminder1_{today_clean}.xlsx",
f"{territory}_email_reminder2_{today_clean}.xlsx"]
new_ref = { orig_file : new_file for orig_file, new_file in zip(files, new_attach) }
msg = EmailMessage()
for filename in files:
with open(filename, 'rb') as file:
file_data = file.read()
new_name = new_ref[file.name]
msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=new_name)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/439633.html
上一篇:認證到期時自動生成電子郵件通知
