Python SMTP:将电子邮件合并为一个 [英] Python SMTP: emails being combined into one

查看:273
本文介绍了Python SMTP:将电子邮件合并为一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是一次将电子邮件发送给两个人.我准备了电子邮件.我遍历两个配对并发送电子邮件.

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.

我有以下代码.

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.

可以解释这种行为并使其不发生吗? SMTP服务器上的某些设置还是邮件头中要设置的某些设置?

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?

推荐答案

该行:

msgRoot['To'] = strTo

不会按照您的想法进行操作-它不会覆盖现有的"To"标题,而是添加了另一个标题.从 docs 中找到:

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

请注意,这不会不会使用以下命令覆盖或删除任何现有的标头 相同的名字.如果要确保新的标头是唯一的 邮件中出现一个字段名称为name的邮件,请删除该字段 首先,例如:

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:将电子邮件合并为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆