import pandas as pd import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import getpass from tkinter import Tk from tkinter.filedialog import askopenfilename # Open file Tk().withdraw() file_path = askopenfilename( title="Select CSV or XLSX file", filetypes=[("CSV files", "*.csv"), ("Excel files", "*.xlsx"), ("All files", "*.*")] ) if not file_path: raise ValueError("No file selected. Exiting.") if file_path.lower().endswith('.csv'): df = pd.read_csv(file_path) elif file_path.lower().endswith(('.xlsx', '.xls')): df = pd.read_excel(file_path) else: raise ValueError("Unsupported file type. Only CSV or XLSX allowed.") # Recipient column print(f"Available columns: {list(df.columns)}") recipient_col = input("Enter the column name for recipients: ").strip() if recipient_col not in df.columns: raise ValueError(f"Column '{recipient_col}' not found.") placeholders = {} while True: var_name = input("Enter a placeholder name (e.g., $Variable1) or press Enter to finish: ").strip() if not var_name: break col_name = input(f"Enter the column name to use for {var_name}: ").strip() if col_name not in df.columns: print(f"Column '{col_name}' not found, try again.") continue placeholders[var_name] = col_name sender_email = input("Enter your sender email address: ").strip() while True: smtp_password = getpass.getpass("Enter your email password (hidden): ") smtp_server = input("Enter your SMTP server (e.g., smtp.gmail.com): ").strip() smtp_port = int(input("Enter your SMTP port (usually 587 for TLS): ").strip()) try: with smtplib.SMTP(smtp_server, smtp_port) as server: server.starttls() server.login(sender_email, smtp_password) print("Login successful!") break except smtplib.SMTPAuthenticationError: print("Authentication failed. Please try again.") except Exception as e: print(f"SMTP error: {e}. Please try again.") subject = input("Enter the email subject: ").strip() print("Enter your email body. Use placeholders like $Variable1, $Variable2.") print("Type 'END' on a new line to finish:") lines = [] while True: line = input() if line.strip().upper() == "END": break lines.append(line) body_template = "\n".join(lines) # send with smtplib.SMTP(smtp_server, smtp_port) as server: server.starttls() server.login(sender_email, smtp_password) for idx, row in df.iterrows(): recipient = row[recipient_col] body = body_template for var, col in placeholders.items(): body = body.replace(var, str(row[col])) msg = MIMEMultipart() msg['From'] = sender_email msg['To'] = recipient msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) try: server.send_message(msg) print(f"Email sent to {recipient}") except Exception as e: print(f"Failed to send email to {recipient}: {e}") print("All emails processed!")