import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import os
from datetime import datetime
# Configuration
SMTP_SERVER = 'smtp-mail.outlook.com'
SMTP_PORT = 587
SMTP_USER = ''
SMTP_PASSWORD = ''
# Read the Excel file
df = pd.read_excel('Test.xlsx')
# Get the current month name
current_month = datetime.now().strftime('%B')
# Iterate over each row in the DataFrame
for index, row in df.iterrows():
name = row['Name']
email = row['Email']
attachment_path = row.get('Attachment', None) # Get 'Attachment' column value if it exists
# Clean the attachment path by removing any quotes
if attachment_path:
attachment_path = attachment_path.strip('"')
# Print debug statements
print(f"Processing email for {name} <{email}> with attachment {attachment_path}")
# Create the email`your text`
msg = MIMEMultipart()
msg['From'] = SMTP_USER
msg['To'] = email
msg['Subject'] = f'{current_month} Payslip' # Set the email subject with the current month
# Email body
body = " "
msg.attach(MIMEText(body, 'plain'))
# Attach the file if the attachment path is provided and the file exists
if attachment_path and os.path.isfile(attachment_path):
try:
with open(attachment_path, "rb") as attachment:
part = MIMEBase('application', 'image/jpeg')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f"attachment; filename= {os.path.basename(attachment_path)}")
msg.attach(part)
print(f"Attached file {attachment_path} for {email}")
except Exception as e:
print(f'Failed to read attachment for {email}. Error: {str(e)}')
continue # Skip sending the email if there's an issue with the attachment
else:
print(f"No valid attachment found for {email}")
# Send the email
try:
server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
server.starttls()
server.login(SMTP_USER, SMTP_PASSWORD)
server.sendmail(SMTP_USER, email, msg.as_string())
print(f'Email sent to {email}')
except Exception as e:
print(f'Failed to send email to {email}. Error: {str(e)}')
finally:
server.quit()
I am trying to attach files from an excel spreadsheet. My code doesn’t seem able to recognise the file paths I have in an “Attachment” column I have in my spreadsheet. The rest of the email prints correctly.
I’ve tried moving the files to another folder to see if it’s a permissions problem, but that didn’t work.
Any ideas are greatly appreciated!
New contributor
Jamie is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.