python: How to send email using smtplib

This article shows how to send email by using python’s smtplib:

1. The environment

Here is the python version I used.

➜  ~ python --version
Python 2.7.10

2. The Code

Now we want to send email using python’s smtplib, here is the code:

# coding=UTF-8

"""
send email example.
"""

import smtplib

SERVER = "mail.xxx.com"

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


SUBJECT = "The subject of email"

TEXT = "The content of email"

# Prepare actual message


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

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

# Send the mail


server = smtplib.SMTP(SERVER)
server.login("[email protected]", "xxxxxxx")
server.sendmail(FROM, TO, message)
print "send mail ok"
server.quit()

3. Run the example

Now run example, we got this

send mail ok

As the upper code shown, we must provice smtplib with follows:

  • the smtp server address including the ip and port
  • the smtp account
  • the smtp password

And then , we supply the subject/content/from/to, be care of the to, it must be a list.

You can find detail documents about the python smtplib here: