Python SMTP: emails being combined into one

2019-07-27 17:28发布

The objective is to send the email to two people at a time. I prepare the email message. I iterate over the pairs and send emails.

I have the following code.

msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'SUBJECT'
msgRoot['From'] = formataddr(('SENDER NAME', strFrom))
msgRoot.preamble = 'This is a multi-part message in MIME format.'

# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)

msgText = MIMEText('PLAINTEXT')
msgAlternative.attach(msgText)

# We reference the image in the IMG SRC attribute by the ID we give it below
with open('index.htm', 'r') as fp:
    msgText = MIMEText(fp.read(), 'html')
msgAlternative.attach(msgText)

# This example assumes the image is in the current directory
with open('download.png', 'rb') as fp:
    msgImage = MIMEImage(fp.read())

# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<imagesss>')
msgRoot.attach(msgImage)


conn = smtplib.SMTP('email-smtp.us-east-1.amazonaws.com', 587)
conn.starttls()
conn.login('user', 'password')
for pairs in paired_users:
    strTo = ', '.join(pairs)
    msgRoot['To'] = strTo
    print strTo
    conn.sendmail(strFrom, strTo, msgRoot.as_string())
conn.quit()

As you can clearly see that the emails are being sent separately.

But for some reason when I receive the email, everyone is in the to list. Like there was one email sent out with the send list combined.

Can this behavior be explained and made to not happen? Some setting on the SMTP server or some setting to be set in the message header?

1条回答
放荡不羁爱自由
2楼-- · 2019-07-27 17:34

The line:

msgRoot['To'] = strTo

does not do what you think - it doesn't overwrite the existing 'To' header, it adds another. From the docs for Message.__setitem__:

Note that this does not overwrite or delete any existing header with the same name. If you want to ensure that the new header is the only one present in the message with field name name, delete the field first, e.g.:

>>> del msg['subject']

>>> msg['subject'] = 'Python roolz!'

查看更多
登录 后发表回答