Friday, August 28, 2020

Sending Emails in Python using SMTP



Hello dear readers! welcome back to another section of my tutorial on Python. In this tutorial post, we are going to be discussing about how to send Emails using SMTP.

Simple Mail Transfer Protocol is a protocol, which handles sending e-mail and routing e-mail between mail servers.

The Python Programing provides smtplib module, that defines an SMTP client session object that can be used in sending mail to any internet machine with an SMTP or ESMTP listener daemon.


Syntax

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

import smtplib

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

Parameter Details

Here is the details of the parameters -

  • host - The host that's running your SMTP server. You can specify the IP address of the host or domain name like webdesigntutorialz.com. This is an optional argument.
  • port - If you are providing the host argument, 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 just localhost as of this option.


An SMTP object has an instance method known as sendmail, which is  generally used to do the work of mailing a message. It takes up three parameters -

  • The sender - A string with address of the sender.
  • The receivers - This is a list of strings, one for each of the recipients.
  • The message - A message as string that is formatted as specified in various RFCs.

Example

Following below is a simple way to send one email using the Python script -

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


From the above example, we placed a basic email in message, by using a triple quote, taking care in formating the header correctly. An email needs a From, To, and Subject header, been separated from the body of the email with a blank line.

To send the email you use smtpObj in connecting to SMTP server on the local machine and then make use of the sendmail method along side with the message, the from address, and destination address as parameters.

But if you are not running an SMTP server on your machine, you can use smtplib client to communicate with a remote SMTP server. Unless you are using a webmail service (like Gmail or Yahoo! Mail) your email provider must have provided you with details of the outgoing mail server that you can supply them, as follows -

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


Sending an HTML email using Python

When you send a text message via Python, all the content are treated as simple text. Even if you include Html tags in a text message, it is displayed as simple text and Html tags are not going to be formatted according to the Html syntax. However, Python provides option for sending an Html message as actual Html message.

While sending an email message, you can specify a Mime version, content type and character set to send an Html email -

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

To send an email that has mixed content, is required to set Content-type header to multipart/mixed. The text and attachment sections of the email can then be specified within boundaries.

Boundary starts with two hyphens that is then followed by a unique number, which cannot appear in the message part of the email. A final boundary which denotes the email final section must also end with two hyphens.

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

Example
The following is a simple example, which sends 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 = 'webmaster@webdesigntutorialz.com
reciever = 'novatekz33@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 <novatekz33@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"


Alright guys! This is where we are rounding up for this tutorial post. In my next tutorial, we are going to be discussing about the Python Multithreaded Programing.

Feel feel to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.
Share:

0 comments:

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.