Home > other >  smtplib best way to rename multiple emails
smtplib best way to rename multiple emails

Time:03-08

I have an smtplib function that loops through 2 excel files and then opens them and adds them as an attachment. Right now the have generic names, but I thought it would be pretty cool to grab info from the data and use it as the name of the document. For example I wanted to grab their location based on a "Location" column found in a dataframe if Ive filtered by the user.

Goal: Rename 2 documents currently called "File1.xlsx" and "File2.xlsx" to "location_email_reminder1_3-4-2022" and "location_email_reminder2_3-4-2022"

Here's my code so far:

#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) 

normally if it was a single file, I could just change the name by using the "filename" method, but I'm not sure how to do it for more than 1 file.

CodePudding user response:

You could create a dictionary using the zip function and reference the old name as a key to pass the new desired name to the filename parameter.

...
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)
  • Related