Python Sending Email using SMTP


Contents

The protocol ~ Simple Mail Transfer Protocol (SMTP) is responsible for managing sending e-mail and routing e-mail between the mail servers.

Python contributes smtplib module that describes an SMTP client session object. SMTPLIB can be offered to send mail to every Internet savvy machine with an SMTP or ESMTP listener daemon.

Here is a simple syntax to create one SMTP object, which can later be used to send an e-mail −

import smtplib

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

Here is the detail of the parameters −

  • host − Host runs your SMTP server, where users specify an IP address, and a domain name. This is optional argument.
  • port – Users writing host argument are required to specify a port, where SMTP server is listening. As a rule, this port would be always 25.
  • local_hostname − If your SMTP server is operated on your home machine, then you can identify just localhost as of this alternative.

An SMTP object has an example technique called sendmail, which is characteristically exercised to do the effort of mailing a message. It seizes three parameters −

  • The message − A message as a string formatted as specified in the various RFCs
  • The sender − A string with the address of the sender
  • The receivers − A list of strings, one for each recipient

Example

Here is a simple way to send one e-mail using Python script. Try it once

#!/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"

Here, you possess or put an essential e-mail in message, utilizing a triple quote, captivating heed to format the headers properly. An e-mail needs a From, To, and Subject header, divided from the body of the e-mail with a blank line.

To send the mail you exercise smtpObj to hook up to the SMTP server on the local machine. Once it is done, use the sendmail process along with the message, the from address, and the destination address as parameters (even though the form and to addresses are within the e-mail itself, these aren't always used to route mail).

People installed and running an SMTP server on the local machine can utilize smtplib client to converse with a remote SMTP server. If not you are utilizing a webmail service, your e-mail provider must have share outgoing mail server details with you required for the below mentioned coding:

smtplib.SMTP('mail.your-domain.com', 25)

Sending an HTML e-mail using Python

When users send a text message adopting Python, then entire content are accepted as simple text. Even if users incorporate HTML tags in a text message, which can display as easy text and HTML tags will never be formatted as per HTML syntax. However, Python renders alternative to send an HTML message according to an actual HTML message.

While sending an e-mail message, you can specify a Mime version, content type and character set to send an HTML e-mail.

Example

Following is the example to send HTML content as an e-mail. Try it once −

#!/usr/bin/python

import smtplib

message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test

This is an e-mail message to be sent in HTML format

<b>This is HTML message.</b>
<h1>This is headline.</h1>
"""

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

Sending Attachments as an E-mail

To propel an e-mail with varied content needs to set Content-type header to multipart/mixed. Then, text and attachment sections can be provided within boundaries.

An edge is begun with two hyphens pursued by an inimitable number, which never emerge in the message fraction of the e-mail. A last boundary denoting the e-mail's final part must also end with two hyphens.

Attached files should be encoded with the pack("m") function to have base64 encoding before transmission.

Example

Following is the example, which sends a file /tmp/test.txt as an attachment. Try it once:

#!/usr/bin/python

import smtplib
import base64

filename = "/tmp/test.txt"

# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent)  # base64

sender = 'webmaster@tutorialpoint.com'
reciever = 'amrood.admin@gmail.com'

marker = "AUNIQUEMARKER"

body ="""
This is a test email to send an attachement.
"""
# Define the main headers.
part1 = """From: From Person <me@fromdomain.net>
To: To Person <amrood.admin@gmail.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)

# Define the message action
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit

%s
--%s
""" % (body,marker)

# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s

%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3

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

Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.



Navigation
Tutorial
Tutorial
Tutorial