Python Sending Email

Share on facebook
Share on twitter
Share on linkedin
Share on twitter
Share on tumblr

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.


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



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


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


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

import smtplib
sender = ''
receivers = ['']
message = """From: From Person <>
To: To Person <>
Subject: SMTP e-mail test
This is a test e-mail message.

   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 *