新手求助:如何用Python实现基于输入列表的个性化邮件发送器
Fixing Your Personalized Email Sender
Hey there! Let's get your email sender working properly so it sends personalized messages to each recipient instead of one big email with all names lumped together. Here's what's going wrong and how to fix it step by step:
Key Issues in Your Current Code
- You’re treating the input
to_listandName_listas single strings instead of splitting them into individual entries. That’s why you see "Hi ben, dave" instead of personalized greetings. - You only create one email message and send it once, rather than looping through each recipient to generate a unique email for them.
- There’s no handling for cases where a name is missing (or the name list is shorter than the email list).
- The extra code testing wrong passwords is unnecessary and can be removed—it doesn’t contribute to your core functionality.
Corrected Code with Explanations
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage from itertools import zip_longest # Handles mismatched list lengths gracefully # Email server configuration host = "smtp.gmail.com" port = 587 username = "xxx@gmail.com" password = "xxx" from_email = username # Process user input: split into clean lists to_list = [email.strip() for email in input('Please enter emails separated by a comma: ').split(',')] name_list = [name.strip() for name in input('Please enter names separated by a comma: ').split(',')] # Connect to SMTP server and send emails try: email_conn = smtplib.SMTP(host, port) email_conn.ehlo() email_conn.starttls() email_conn.login(username, password) print("Successfully connected to the email server!") # Loop through each recipient (pair emails with names, fill missing names with blank) for email, name in zip_longest(to_list, name_list, fillvalue=""): # Create a unique message for each recipient (critical for personalization!) the_msg = MIMEMultipart('alternative') the_msg['Subject'] = "Link" the_msg["From"] = from_email the_msg["To"] = email # Target one recipient per email # Set up personalized greeting greeting = f"Hi {name}!" if name else "Hi!" # Plain text content with personalized greeting plain_txt = f"{greeting}\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org" # HTML content with personalized greeting html_txt = f"""\ <html> <head></head> <body> <p>{greeting}<br> How are you?<br> Here is the <a href="http://www.python.org">link</a> you wanted.<br> <img src="cid:image1"> </p> </body> </html> """ # Attach the image fp = open('/Users/xxx/xxx.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>') the_msg.attach(msgImage) # Attach plain text and HTML parts part_1 = MIMEText(plain_txt, 'plain') part_2 = MIMEText(html_txt, "html") the_msg.attach(part_1) the_msg.attach(part_2) # Send the personalized email email_conn.sendmail(from_email, email, the_msg.as_string()) print(f"Successfully sent email to {email}!") except smtplib.SMTPAuthenticationError: print("Error: Wrong username or password!") except smtplib.SMTPException as e: print(f"An SMTP error occurred: {str(e)}") except Exception as e: print(f"Unexpected error: {str(e)}") finally: # Ensure we close the connection even if something goes wrong if 'email_conn' in locals(): email_conn.quit() print("Disconnected from the email server.")
What Changed?
- Input Cleaning: We split input strings into lists and strip extra whitespace, so each email/name is a separate, clean entry.
- Recipient Loop: Using
zip_longestpairs each email with a name, and fills in blank strings for missing names. - Personalized Greeting: We check if a name exists—if yes, use "Hi {name}!", otherwise fall back to "Hi!".
- Unique Messages: A new
MIMEMultipartobject is created inside the loop, so each email is fully independent. - Improved Error Handling: We now catch common issues (like wrong credentials) and properly close the server connection.
- Removed Bloat: Got rid of the unnecessary wrong-password test code that was cluttering your script.
Quick Tips
- For Gmail, if you have 2FA enabled, use an App Password instead of your regular password. If not, enable "Less secure app access" temporarily (though App Passwords are safer).
- Double-check your image file path to ensure it’s correct—mismatched paths will cause the image to not load in emails.
内容的提问来源于stack exchange,提问作者ozwaldsux
相关产品推荐
相关产品推荐

