Email multiple contacts in Python
I am trying to send an email开发者_开发知识库 to multiple addresses. The code below shows what I'm attempting to achieve. When I add two addresses the email does not send to the second address. The code is:
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()
I have tried:
you = ['a@a.com', 'a@a.com']
and
you = 'a@a.com', 'a@a.com'
Thanks
You want this:
from email.utils import COMMASPACE
...
you = ["foo@example.com", "bar@example.com"]
...
msg['To'] = COMMASPACE.join(you)
...
s.sendmail(me, you, msg.as_string())
Try
s.sendmail(me, you.split(","), msg.as_string())
If you do you = ['a@a.com', 'a@a.com']
Try
msg['To'] = ",".join(you)
...
s.sendmail(me, you, msg.as_string())
you = ('one@address', 'another@address')
s.sendmail(me, you, msg.as_string())
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())
In the example to read emails from the configuration file, for example configparser - pip install configparser
.
- In the created
config.ini
file we add the code from below:
[mail]
SENDER = me@mail.com
RECEIVERS = foo@mail.com,bar@mail.com
- Create another
test.py
file located in the same directory
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()
精彩评论