codescracker


python

Python Sending Email



« Previous Tutorial Next Tutorial »


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 codescracker.com 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 = '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"

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test