通过Python发送多个联系人

时间:2010-01-05 14:34:45

标签: python

我正在尝试向多个地址发送电子邮件。下面的代码显示了我正在尝试实现的目标。当我添加两个地址时,电子邮件不会发送到第二个地址。代码是:

   me = 'a@a.com'
   you = 'a@a.com, a@a.com'
   msg['Subject'] = "Some Subject"
   msg['From'] = me
   msg['To'] = you

   # Send the message via our own SMTP server
   s = smtplib.SMTP('a.a.a.a')
   s.sendmail(me, [you], msg.as_string())
   s.quit()

我试过了:

you = ['a@a.com', 'a@a.com']

you = 'a@a.com', 'a@a.com'

由于

4 个答案:

答案 0 :(得分:12)

尝试

s.sendmail(me, you.split(","), msg.as_string())

如果你you = ['a@a.com', 'a@a.com']

尝试

msg['To'] = ",".join(you)

...

s.sendmail(me, you, msg.as_string())

答案 1 :(得分:10)

你想要这个:

from email.utils import COMMASPACE
...
you = ["foo@example.com", "bar@example.com"]
...
msg['To'] = COMMASPACE.join(you)
...
s.sendmail(me, you, msg.as_string())

答案 2 :(得分:2)

you = ('one@address', 'another@address')
s.sendmail(me, you, msg.as_string())

答案 3 :(得分:0)

import smtplib
from email.mime.text import MIMEText

s = smtplib.SMTP('smtp.foobar.com')
msg = MIMEText("""body""")
sender = 'me@mail.com'
recipients = ['foo@mail.com', 'bar@mail.com']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())

在该示例中,从配置文件中读取电子邮件,例如configparser-pip install configparser

  • 在创建的config.ini文件中,我们从下面添加代码:
[mail]
SENDER    = me@mail.com
RECEIVERS = foo@mail.com,bar@mail.com
  • 在同一目录中创建另一个test.py文件
import configparser
import smtplib
from smtplib import SMTPException

config  = configparser.RawConfigParser() 
config.read('config.ini')

# template
msg = """From: From Person <{0}>
To:{1}
MIME-Version: 1.0
Content-type: text/html
Subject: Hello {2}

Check your results :)

{3}
"""

# universal function that would send mail when called
def send_mail(sender, receivers, subject, message):
    try:
        session = smtplib.SMTP(host = "ip", port = 25)
        session.ehlo()
        session.starttls()
        session.ehlo()
        session.sendmail(sender, receivers, msg.format(sender, receivers, subject, message)) 
        session.quit()
        print("Your mail has been sent successfuly! Thank you for your feedback!")
    except SMTPException:
        print("Error: Unable to send email.")

# html context for email
your_subject = "SMTP HTML e-mail test"
your_message = """This is an e-mail message to be sent in HTML format
<b>This is HTML message.</b>
<h1>This is headline.</h1>
"""

# The call to the universal e-mail function to which we pass the parameters in this example are given above
def setup_and_send_mail():
    send_mail(config.get('mail', 'SENDER'), (config.get('mail', 'RECEIVERS')), your_subject, your_message) 


if __name__ == "__main__":

    setup_and_send_mail()