1

I am trying to send an email to two userid's using the below code,any idea what is wrong?how to send to multiple recipients?

def email1(body,subject):
    print "In email1"
    msg = MIMEText("%s" % body)
    msg['Content-Type'] = "text/html; charset=UTF8"
    msg['Subject'] = subject
    s = SMTP('localhost',25)
    s.sendmail('userid@company.com', ['userid1@company.com','userid2@company.com'],msg=msg.as_string())

1 Answers1

3

Organize the function into more reusable form:

from smtplib import SMTP
from email.mime.text import MIMEText

def send_email(body, subj, frm, to, host='localhost', port=25):
    msg = MIMEText(body)
    msg['Content-Type'] = 'text/html; charset=UTF8'
    msg['Subject'] = subj
    msg['From'] = frm
    msg['To'] = ', '.join(to) if type(to) == list else to
    smtp = SMTP(host, port)
    smtp.sendmail(frm, to, msg=msg.as_string())

to test it use the built-in SMTP server, run it on port 3000 from the command line using:

python -msmtpd -n -c DebuggingServer localhost:3000

and send some emails:

>>> send_email('Message', 'Spam', 'me@foo.com', ['u1@foo.com', 'u2@foo.com'], port=3000)
>>>
>>> send_email('Message', 'Spam', 'me@foo.com', 'u1@foo.com', port=3000)
>>>

You should see:

> python -msmtpd -n -c DebuggingServer localhost:3000
---------- MESSAGE FOLLOWS ----------
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Type: text/html; charset=UTF8
Subject: Spam
From: me@foo.com
To: u1@foo.com, u2@foo.com
X-Peer: 127.0.0.1

Message
------------ END MESSAGE ------------
---------- MESSAGE FOLLOWS ----------
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Type: text/html; charset=UTF8
Subject: Spam
From: me@foo.com
To: u1@foo.com
X-Peer: 127.0.0.1

Message
------------ END MESSAGE ------------