问题描述
import smtplib
from email.message import EmailMessage
list1=[
'Person 1 <email1@outlook.com>','Person 2 <[email protected]>'
]
list2=[
'Person 3 <[email protected]>','Person 4 <[email protected]>'
]
masterlist = [list1,list2]
for x in masterlist:
receivers = ",".join(x)
msg = EmailMessage()
msg['Subject'] = 'This is a Test Email'
msg['From'] = 'Person 5 <email5@outlook.com>'
msg['To'] = receivers
msg.set_content('Ignore this message')
with smtplib.SMTP('smtp.outlook.com',587) as smtp:
smtp.send_message(msg)
这是我使用的代码。我想将此电子邮件发送给某些组,但不将所有电子邮件合并为一封电子邮件。我现在拥有的方式只是最终将电子邮件发送到最后的电子邮件列表中。我应该如何修改才能将其发送到多个电子邮件列表?
解决方法
您只将电子邮件的最后一个列表传递给msg['To']
,因为该程序会用lst中的最后一项覆盖先前的lst分配。那么,为什么只希望将两个列表连接起来以向所有人发送电子邮件?
#masterlist = [list1,list2]
#for x in masterlist:
#receivers = ",".join(x)
# The .join() function doesn't do much in this situation because your lists are already separated by commas.
msg = EmailMessage()
msg['Subject'] = 'This is a Test Email'
msg['From'] = 'Person 5 <[email protected]>'
msg['To'] = list1 + list2 # or use .extend() function the same is accomplished
msg.set_content('Ignore this message')
因此,请摆脱masterlist
变量和for
循环。
import smtplib
from email.message import EmailMessage
list1=[
'Person 1 <[email protected]>','Person 2 <[email protected]>'
]
list2=[
'Person 3 <[email protected]>','Person 4 <[email protected]>'
]
masterlist = [list1,list2]
for x in masterlist:
msg = EmailMessage()
msg['Subject'] = 'This is a Test Email'
msg['From'] = 'Person 5 <[email protected]>'
msg['To'] = x
msg.set_content('Ignore this message')
with smtplib.SMTP('smtp.outlook.com',587) as smtp:
smtp.send_message(msg)
我能够通过根据电子邮件列表将“电子邮件”部分放入for循环来纠正此问题。