Python Sending Email

In this Python tutorial, let us discuss about sending an email using Python script with appropriate examples.

Introduction of Python Sending Email

Simple Mail Transfer Protocol (SMTP) is a protocol that handles sending and routing of e-mail between mail servers.

Python gives the smtplib module, which defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.

Syntax

import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

Parameters 

host

This is the host running your SMTP server. You can specify the IP address of the host or a domain name like tutorialspoint.com. This is an optional argument.

port

If you are providing host argument, then you need to specify a port, where SMTP server is listening. Usually, this port would be 25.

local_hostname

If your SMTP server is running on your local machine, then you can specify just localhost as of this option.

Example code to send one e-mail using Python script

#!/usr/bin/python
import smtplib
sender = 'from@fromdomain.com'
receivers = ['to@todomain.com']
message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
Subject: SMTP e-mail test
This is a test e-mail message.

"""
try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, receivers, message)         
  print "Successfully sent email"
except SMTPException:
   print "Error: unable to send email"

Output for the code

"Successfully sent email"

                                  

Leave a Comment

Your email address will not be published. Required fields are marked *