How to send an email with Python?


This code works and sends me an email just fine:

import smtplib
#SERVER = "localhost"

FROM = "[email protected]"

TO = ["[email protected]"] # must be a list

SUBJECT = "Hello!"

TEXT = "This message was sent with Python"s smtplib."

# Prepare actual message

message = """
From: %s
To: %s
Subject: %s

""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail

server = smtplib.SMTP("myserver")
server.sendmail(FROM, TO, message)

However if I try to wrap it in a function like this:

    import smtplib
    """this is some test documentation in the function"""
    message = """
        From: %s
        To: %s
        Subject: %s
        """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
    # Send the mail
    server = smtplib.SMTP(SERVER)
    server.sendmail(FROM, TO, message)

and call it I get the following errors:

 Traceback (most recent call last):
  File "C:/Python31/", line 8, in <module>
  File "C:/", line 13, in sendMail
    server.sendmail(FROM, TO, message)
  File "", line 720, in sendmail
  File "", line 444, in rset
    return self.docmd("rset")
  File "", line 368, in docmd
    return self.getreply()
  File "", line 345, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

Can anyone help me understand why?

Answer rating: 205

I recommend that you use the standard packages email and smtplib together to send email. Please look at the following example (reproduced from the Python documentation). Notice that if you follow this approach, the "simple" task is indeed simple, and the more complex tasks (like attaching binary objects or sending plain/HTML multipart messages) are accomplished very rapidly.

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we"ll need
from email.mime.text import MIMEText

# Open a plain text file for reading.  For this example, assume that
# the text file contains only ASCII characters.
with open(textfile, "rb") as fp:
    # Create a text/plain message
    msg = MIMEText(

# me == the sender"s email address
# you == the recipient"s email address
msg["Subject"] = "The contents of %s" % textfile
msg["From"] = me
msg["To"] = you

# Send the message via our own SMTP server, but don"t include the
# envelope header.
s = smtplib.SMTP("localhost")
s.sendmail(me, [you], msg.as_string())

For sending email to multiple destinations, you can also follow the example in the Python documentation:

# Import smtplib for the actual sending function
import smtplib

# Here are the email package modules we"ll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

# Create the container (outer) email message.
msg = MIMEMultipart()
msg["Subject"] = "Our family reunion"
# me == the sender"s email address
# family = the list of all recipients" email addresses
msg["From"] = me
msg["To"] = ", ".join(family)
msg.preamble = "Our family reunion"

# Assume we know that the image files are all in PNG format
for file in pngfiles:
    # Open the files in binary mode.  Let the MIMEImage class automatically
    # guess the specific image type.
    with open(file, "rb") as fp:
        img = MIMEImage(

# Send the email via our own SMTP server.
s = smtplib.SMTP("localhost")
s.sendmail(me, family, msg.as_string())

As you can see, the header To in the MIMEText object must be a string consisting of email addresses separated by commas. On the other hand, the second argument to the sendmail function must be a list of strings (each string is an email address).

So, if you have three email addresses: [email protected], [email protected], and [email protected], you can do as follows (obvious sections omitted):

to = ["[email protected]", "[email protected]", "[email protected]"]
msg["To"] = ";".join(to)
s.sendmail(me, to, msg.as_string())

the ";".join(to) part makes a single string out of the list, separated by commas.

From your questions I gather that you have not gone through the Python tutorial - it is a MUST if you want to get anywhere in Python - the documentation is mostly excellent for the standard library.

Answer rating: 82

Well, you want to have an answer that is up-to-date and modern.

Here is my answer:

When I need to mail in Python, I use the mailgun API wich get"s a lot of the headaches with sending mails sorted out. They have a wonderfull app/api that allows you to send 5,000 free emails per month.

Sending an email would be like this:

def send_simple_message():
        auth=("api", "YOUR_API_KEY"),
        data={"from": "Excited User <[email protected]_DOMAIN_NAME>",
              "to": ["[email protected]", "[email protected]_DOMAIN_NAME"],
              "subject": "Hello",
              "text": "Testing some Mailgun awesomness!"})

You can also track events and lots more, see the quickstart guide.

I hope you find this useful!