×

Python Sending Email

Python Sending Email

Simple Mail Transfer Protocol (SMTP) is used to handle sending e-mail and routing e-mail between mail servers. When we send an email either form a web-application or from a local software running in our computer, our computer packages the message and sends it using SMTP.

There are many open, free-to-use SMTP servers, but these are frequently used by spammers and blocked by most incoming mail servers. It is better to use a password-protected SMTP server because your mail will likely reach the recipient instead of getting filtered and dumped into the recipient’s spam folder.

A typical email requires the following parameters:

  • Recipient email address
  • Sender email address
  • Message Subject
  • Message Body
  • Attachments (if any, not required)
  • SMTP server address
  • SMTP port (usually 25, but could also be 2525 or 587 as alternatives)

Python provides smtplib module, which describes an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener deamon. The syntax is following:

import smtplib
smtpObj = smtplib.SMTP( [host [, port_no [, local_hostname]]] )
  • host:  Host runs in SMTP server. You can specify the IP address of the host or a domain name like tutorialandexample.com. The host is an optional argument.
  • port_no: It is necessary to provide the port number if we are giving host argument.
  • local_hostname: If the SMTP server is running on your local machine, then you can specify just localhost for this option.

An SMTP object has an instance method called sendmail, which is typically used to do work of mailing a message. It accepts three parameters-

  • The sender - A string with the address of the sender.
  • The receiver - A list of strings, one for each recipient.
  • The message – A message as a string formatted as stated in the various RFCs.

Sending email using SMTP

import smtplib
sender_mail = 'sender@fromdomain_name.com'
receivers_mail = ['reciever@todomain_name.com']
message = """From: From Person %s 
To: To Person %s 
Subject: Sending SMTP e-mail  
This is a test e-mail message. 
"""%(sender_mail,receivers_mail)
try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender_mail, receivers_mail, message)
   print("Successfully sent email")
except Exception:
   print("Error: unable to send email")

Sending email using Gmail

In the few cases where emails are sent using Gmail SMTP server. In this case, we can pass gmail as the SMTP server instead of using localhost with the port 587.

Using the Gmail account, we need to login to the Gmail account using Gmail user name and password. The smtplib provides the login() function which takes the username and password of the sender.

import smtplib  
sender_mail = 'senderemail_address@gmail.com'  
receivers_mail = ['receiver_email@gmail.com']  
message = """From: From Person %s 
To: To Person %s 
Subject: Sending SMTP e-mail  
This is a test e-mail message. 
"""%(sender_mail,receivers_mail)  
try:  
   password = input('Enter the password');  
   smtpObj = smtplib.SMTP('gmail.com',587)  
   smtpobj.login(sender_mail,password)  
   smtpObj.sendmail(sender_mail, receivers_mail, message)  
   print("Email sent successfully")  
except Exception:  
   print("Error: unable to send email")  

Sending an HTML using Python

When we try to send a text message using the Python, all content is treated as simple text.  If we include the HTML tags in a text message, it is treated as simple text and HTML tags will not be formatted according to HTML syntax. But Python allows an option to send an HTML message as actual HTML message.

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

import smtplib
sender_mail = 'sender@fromdomain.com'
receivers_mail = ['reciever@todomain.com']
message = """From: From Person %s 
To: To Person %s 
MIME-Version:1.0 
Content-type:text/html 
Subject: Sending SMTP e-mail  
<h3>SMTP Example</h3> 
<em>This is a test e-mail message.</em> 
""" % (sender_mail, receivers_mail)
try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender_mail, receivers_mail, message)
    print("Successfully sent email")
except Exception:
    print("Error: unable to send email")

Related Topics

Python Subprocess Call Example

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

4 minutes read.

Struct Module in Python

What is a structure in Python? An entity that holds data in form of a structure is called a data structure. In Python, the data structure includes tuples, lists, dictionaries, and...

4 minutes read.

Reading a File Line by Line in Python

Introduction In this tutorial, we will learn about reading files in python line by line. Before reading the files, let us know a little information about the files first. Files A file is...

6 minutes read.

Python Dictionary pop() method

Python Dictionary pop() method The dictionary.pop() method in removes the specified item and returns an element from a dictionary having the given key. Syntax dictionary.pop(key[, default]) Parameter key – This argument signifies the key which is to...

2 minutes read.

Sentence to python vector

Conversion of a Sentence to Vector in Python Before starting the tutorial, let’s just recap about the vector and the respective package that has to be imported in Python. Python Vector: Putting simply,...

3 minutes read.

Speech Recognition in Python

What is Speech Recognition? Speech Recognition is a term defined for automatic recognition of human speech. Speech recognition is the most significant activity in the domain of the interaction between the...

8 minutes read.

Character Set in Python

A collection of legal characters that will recognize by a programming language known as a Character set. Taking python programming language as an instance. The set of characters supported by the...

6 minutes read.

API Requests using Python

What is an API? API stands for Application Programming Interface. It is commonly known as API. It provides an environment that helps two or more computer programs to contact each other....

5 minutes read.

Isreal() Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

4 minutes read.

Returning Multiple Values in Python

Python is considered a general-purpose programming language; it is a high-level programming language that is not much difficult and easier to learn. It is rich in libraries that can be...

3 minutes read.

Exponentiation in Python

What is an Exponent in Python? Exponent is a fundamental mathematical concept that is used in many different areas, such as engineering, physics, and finance. In mathematics, an exponent is a...

4 minutes read.

Python maketrans() function

Introduction A static method is the string maketrans() one. It is used to make a one-to-one mapping between a string's character and its translation, i.e., to define the list of characters...

5 minutes read.

Python Simple Interest

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.

Genetic Algorithm in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The source...

4 minutes read.

How to assign values to variables in Python and other languages?

Python makes it simple to construct variables. The value to be stored in the variable should then be written after a suitable name for the variable and the equality sign....

3 minutes read.

Read JSON File in Python

JSON refers to the JavaScript Object Notation. It is a Data format used for representing structured data and it is used to transfer and store data. In JSON format, the...

5 minutes read.

Python Statistical Module

Python Statistical Module The Python statistical module provides various functions that we can use in our Python program, to perform mathematical statistics operations on the numerical data given to us. The...

8 minutes read.

Python Pass Statement

The pass statement is a null statement. The difference between pass and comment is that comment is ignored by the interpreter, whereas pass is not. The pass statement is typically used...

3 minutes read.

apply() function in python

Pandas: Pandas is a library in python. It is an open source package in python. Pandas in python are used for data cleaning and data analysis. Data frame mainly consists of...

3 minutes read.

Python String replace() method

Python String replace() method The string.replace() method in Python returns a copy of the string with all occurrences of substring old replaced by new. Syntax replace(old, new[, count]) Parameter old: This parameter represents a substring you want to...

2 minutes read.