Python SMTP: emails being combined into one

∥☆過路亽.° 提交于 2019-12-11 07:15:43

问题


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:


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!'



来源:https://stackoverflow.com/questions/50301172/python-smtp-emails-being-combined-into-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!