如何在 Python 代码中向多个地址发送电子邮件?
#!/usr/bin/python
import smtplib
import sys, getopt
recipient=''
subject=''
body=''
try:
myopts, args = getopt.getopt(sys.argv[1:],"r:s:m:")
except getopt.GetoptError as e:
print (str(e))
print("Usage: %s -r recipient -s subject -m message" % sys.argv[0])
sys.exit(2)
for o, a in myopts:
if o == '-r':
recipient=a
elif o == '-s':
subject=a
elif o == '-m':
body=a
server = 'smtp.gmail.com'
port = 587
sender = 'foo@bar'
password = 'password'
headers = ["From: " + sender,
"Subject: " + subject,
"To: " + recipient,
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
session = smtplib.SMTP(server, port)
session.ehlo()
session.starttls()
session.ehlo
session.login(sender, password)
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
session.quit()
答案1
准备一个字符串列表,每个字符串对应一个收件人,如下所示:
recipients = ['[email protected]', '[email protected]']
session.sendmail(sender, recipients, headers + "\r\n\r\n" + body)