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 (Startup, Drive, Turbo Boost, or Turbo Max)
  • Reseller hosting
  • Managed WordPress hosting
For these hosting packages, you must use A2 Hosting servers. Other hosting packages have fewer restrictions, and can use some 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:

#!/usr/bin/python

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.
"""

try:
    s = smtplib.SMTP('localhost')
    s.login('[email protected]', 'password')
    s.sendmail(from_addr, to_addrs, msg)
    s.quit()
except smtplib.SMTPException:
    print "Error:", sys.exc_info()[0]
@babblebit.net>@a2example.com>

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 https://docs.python.org/2/library/smtplib.html.

Did you find this article helpful? Then you'll love our support. Experience the A2 Hosting difference today and get a pre-secured, pre-optimized website. Check out our web hosting plans today.

We use cookies to personalize the website for you and to analyze the use of our website. You consent to this by clicking on "I consent" or by continuing your use of this website. Further information about cookies can be found in our Privacy Policy.