Knowledge Base

How to send e-mail messages using Python

This article demonstrates how to send e-mail messages using Python scripts.

You cannot use external SMTP servers to send e-mail messages if you have one of the following hosting packages:
  • Web hosting (Lite, Swift, or Turbo)
  • Reseller hosting
For these hosting packages, you must use A2 Hosting servers. All other hosting packages are not subject to this restriction, and can use external SMTP servers to send e-mail messages.

Using Python to send e-mail messages

Python's smtplib module makes it easy to send e-mail messages from a script. To do this, you create an instance of the SMTP class, which contains all of the functionality you need to connect to a mail server and send messages.

The following sample code demonstrates how to send an e-mail message from an A2 Hosting server using the SMTP class. In your own code, replace [email protected] with the intended message recipient, and [email protected] with the return e-mail address. For the login() method, specify the account username and password that you want to use to authenticate to the SMTP server:


import sys
import smtplib

from_addr = '[email protected]'
to_addrs = ['[email protected]']
msg = """From: Sender
To: Recipient
Subject: This is the message subject

This is the message body.

    s = smtplib.SMTP('localhost')
    s.login('[email protected]', 'password')
    s.sendmail(from_addr, to_addrs, msg)
except smtplib.SMTPException:
    print "Error:", sys.exc_info()[0]

As you can see, this script defines the message, and then constructs an instance of the SMTP class. After the class instance is created, all you need to do is log in to the server and send the message using the sendmail() method.

This is a very simple example that demonstrates basic functionality provided by the SMTP class. To view the official documentation for the smtplib module (including the SMTP class), please visit