目标是一次将电子邮件发送给两个人。我准备电子邮件。我迭代这些对并发送电子邮件。
我有以下代码。
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()
您可以清楚地看到电子邮件是单独发送的。
但由于某种原因,当我收到电子邮件时,每个人都在列表中。就像发送了一封电子邮件并合并了发送列表一样。
可以解释这种行为并使其不发生吗? SMTP 服务器上的某些设置或邮件 header 中要设置的某些设置?
最佳答案
行:
msgRoot['To'] = strTo
不会做你想的那样 - 它不会覆盖现有的“To” header ,而是添加另一个 header 。来自 docs对于 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!'
关于Python SMTP : emails being combined into one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50301172/