简体   繁体   English

如何在 python 中向多个组发送 smtplib 电子邮件?

[英]How can I send an smtplib email to mulitple groups in python?

import smtplib
from email.message import EmailMessage

list1=[
    'Person 1 <email1@outlook.com>',
    'Person 2 <email2@gmail.com>'
    ]
    
list2=[
    'Person 3 <email3@yahoo.com>',
    'Person 4 <email4@hotmail.com>'
    ]
    
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)

This is the code that I have used.I would like to send this email out to certain groups, but not join all emails into one email.这是我使用的代码。我想将此电子邮件发送给某些组,但将所有电子邮件合并为一封电子邮件。 The way I have it now, only ends up sending the email out to the last list of emails.我现在拥有它的方式,最终只会将电子邮件发送到最后一个电子邮件列表。 How should I modify this to be able to send it to multiple lists of emails?我应该如何修改它才能将其发送到多个电子邮件列表?

You're only passing the last list of emails to msg['To'] because the program overwrites the previous lst assignments with last item in lst.您只是将最后一封电子邮件列表传递给msg['To']因为程序用 lst 中的最后一项覆盖了之前的 lst 分配。 So why want you just concatenate the two lists to send the email to everyone?那么为什么要将两个列表连接起来以将电子邮件发送给所有人?

#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 <email5@outlook.com>'
msg['To'] = list1 + list2 # or use .extend() function the same is accomplished
msg.set_content('Ignore this message')

So just get rid of the masterlist variable and the for loop.所以只需摆脱masterlist变量和for循环。

import smtplib
from email.message import EmailMessage

list1=[
    'Person 1 <email1@outlook.com>',
    'Person 2 <email2@gmail.com>'
    ]
    
list2=[
    'Person 3 <email3@yahoo.com>',
    'Person 4 <email4@hotmail.com>'
    ]
    
masterlist = [list1, list2]

for x in masterlist:
    msg = EmailMessage()
    msg['Subject'] = 'This is a Test Email'
    msg['From'] = 'Person 5 <email5@outlook.com>'
    msg['To'] = x
    msg.set_content('Ignore this message')

    with smtplib.SMTP('smtp.outlook.com', 587) as smtp:
        smtp.send_message(msg)

I was able to correct this by making the email section in to a for loop based on the list of emails.我能够通过根据电子邮件列表将电子邮件部分放入 for 循环来更正此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM