Python SMTP问题:邮件收件人列表被合并,如何解决?
Hey there! I’ve run into this exact issue before—let’s break down what’s happening and how to fix it.
The root problem is that you’re reusing the same msgRoot MIME message object for every pair of recipients. When you update msgRoot['To'] in each loop iteration, you’re not replacing the existing To header—you’re actually adding a new one to the message. Email clients will combine all these duplicate To headers when displaying the email, making it look like every recipient was included in a single mass email instead of separate pairs.
Think of it like writing on a piece of paper: if you don’t grab a new sheet for each letter, you just keep adding new addresses to the top, and everyone ends up seeing all the names.
You need to move the entire message construction inside your loop. That way, every pair gets a fresh, clean MIME object with only their two addresses in the To header. Here’s how to adjust your code:
conn = smtplib.SMTP('email-smtp.us-east-1.amazonaws.com', 587) conn.starttls() conn.login('user', 'password') for pairs in paired_users: # Create a NEW message object for each recipient pair msgRoot = MIMEMultipart('related') msgRoot['Subject'] = 'SUBJECT' msgRoot['From'] = formataddr(('SENDER NAME', strFrom)) msgRoot.preamble = 'This is a multi-part message in MIME format.' # Encapsulate plain and HTML bodies msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText('PLAINTEXT') msgAlternative.attach(msgText) with open('index.htm', 'r') as fp: msgText = MIMEText(fp.read(), 'html') msgAlternative.attach(msgText) # Attach the image with open('download.png', 'rb') as fp: msgImage = MIMEImage(fp.read()) msgImage.add_header('Content-ID', '<imagesss>') msgRoot.attach(msgImage) # Set recipients and send strTo = ', '.join(pairs) msgRoot['To'] = strTo print(strTo) conn.sendmail(strFrom, pairs, msgRoot.as_string()) # Use the list `pairs` instead of string for sendmail conn.quit()
A couple of extra tips:
- I changed
conn.sendmail(strFrom, strTo, ...)to usepairsdirectly (the list of recipients) instead of the comma-separated string. SMTP’ssendmailworks more reliably with a list of addresses, avoiding any parsing mishaps. - By rebuilding the entire message each time, you ensure there’s no leftover header data from previous iterations.
Nope! This is purely a code issue with how you’re reusing the MIME message object. Your SMTP server configuration is fine—no changes needed there. The fix is all about making sure each email gets its own fresh message container.
内容的提问来源于stack exchange,提问作者Sam Thomas

