Python SMTP:将电子邮件合并为一个

时间:2018-05-11 22:44:06

标签: python email smtp amazon-ses

目标是一次向两个人发送电子邮件。我准备了电子邮件。我迭代对并发送电子邮件。

我有以下代码。

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服务器上的某些设置或要在邮件头中设置的某些设置?

1 个答案:

答案 0 :(得分:2)

该行:

msgRoot['To'] = strTo

不符合您的想法 - 它不会覆盖现有的&#39; To&#39;标题,它增加了另一个。来自Message.__setitem__的{​​{3}}:

  

请注意,会覆盖或删除任何现有标头   同名。如果要确保新标头是唯一的   一个存在于带有字段名称的消息中,删除该字段   首先,例如:

     

>>> del msg['subject']

     

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