python邮件合并的基本操作步骤_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.

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', '')

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?

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值