SENDING MAIL IN PYTHON - Complete Guide For Python Programming (2015)

Complete Guide For Python Programming (2015)

SENDING MAIL IN PYTHON

Simple Mail Transfer Protocol (SMTP) is a protocol that is used to send e-mails and routing e-mails between the mail servers. In Python there is 'smtplib' module, which defines an SMTP client session object. SMTP client session object is 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]]])

Detail of parameters used:

host: This is the host running your SMTP server. You can specify IP address of the host or a domain name. This is 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 justlocalhost as of this option. An SMTP object has an instance method called sendmail, which will typically be used to do the work of mailing a message. It takes three parameters:

The sender - A string with the address of the sender.

The receivers - A list of strings, one for each recipient.

The message - A message as a string formatted as specified in the various RFCs.

Example:

To send an e-mail using Python script.

#!/usr/bin/python

import smtplib

sender = 'abc@senddomain.com'

receivers = ['xyz@recdomain.com']

message = """From: From Person <abc@senddomain.com>

To: To Person <xyz@recdomain.com>

Subject: SMTP e-mail test

This is a test e-mail message.

"""

try:

smtpObj = smtplib.SMTP('localhost')

smtpObj.sendmail(sender, receivers, message)

print "Mail sent successfully"

except SMTPException:

print "Error in sending mail"

In case, if you are not running an SMTP server on your local machine, then you can use 'smtplib' client to communicate with a remote SMTP server. Unless you're using a webmail service, your e-mail provider will have provided you with outgoing mail server details that you can provide them, as follows:

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

Sending an HTML E-mails Using Python:

When you send a text message using Python, then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But Python provides option to send an HTML message as 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 to send HTML content as an e-mail:

#!/usr/bin/python

import smtplib

message = """From: From Person <abc@senddomain.com>

To: To Person <xyz@recdomain.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>Here is HTML text for you.</b>

<h1>Here is Headline for you.</h1>

"""

try:

smtpObj = smtplib.SMTP('localhost')

smtpObj.sendmail(sender, receivers, message)

print "Mail sent successfully"

except SMTPException:

print "Error in sending mail"

Sending Attachments as an e-mail:

To send an e-mail with mixed content requires setting Content-type header to multipart/mixed. Then, text and attachment sections can be specified within boundaries. A boundary is started with two hyphens followed by a unique number, which can not appear in the message part of the e-mail. A final boundary denoting the e-mail's final section must also end with two hyphens. Attached files should be encoded with the pack("m") function to have base64 encoding before transmission.

Example to send a file /tmp/test.txt as an attachment:

#!/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 = 'test@aaadomain.com'

reciever = 'aaa.admin@gmail.com'

marker = "TESTMARKER"

body ="""

This is a test email to send an attachement.

"""

# Define the main headers.

part1 = """From: From Person <me@fromdomain.net>

To: To Person <aaa.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 "Mail sent successfully"

except Exception:

print "Error in sending email"