Python Sending Email

SMTP stands form Simple Mail Transfer Protocol is simply a protocol, which handles the sending e-mail and routing e-mail between the mail servers. Python provides you a smtplib module, which defines an SMTP client session object, can be used to send a mail to any internet machine with an SMTP/ESMTP listener daemon. Here is the general form to create a SMTP object, that can later be used in sending an e-mail

import smtplib

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

Here, host is the host running your SMTP server. You can specify either IP address or domain name list in the host. Now, port is needed to specify in case you are providing the host argument, where SMTP server is listening. Generally, this port will be 25, and if your SMTP server is running on your local machine, then you are free to specify localhost as of this local_hostname option.

Send E-mail using Python

Here is a simple way to send a e-mail using python script:

# Python Sending Example - Example Program

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"

Python Online Test

« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook

Subscribe Us on YouTube