×

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

How to set font for Text in Python

As a tuple with the font family as the first component, a size in point as the second, and possibly a string with one or more of the style modifiers...

5 minutes read.

Add a key-value pair to dictionary in Python

In programming, data type defines the type of value that a variable can hold. With help of these, we can perform various mathematical, logical, or relational operations on that particular...

5 minutes read.

Python Set discard() method

Python Set discard() method The set.discard() method in Python removes a specified element from the set (if present). Syntax set.discard(value) Parameter value- This parameter represents the element to be removed from the set. Return None Example 1 # Python program explaining # the...

1 minute read.

Python filter() function

Python filter() function The filter() function constructs an iterator from those elements of iterable for which the parameter ‘function’ returns a Boolean value true. Syntax filter(function, iterable) Parameter function: This parameter represents a function to be run for each item in the...

1 minute read.

XGBoost for Regression in Python

Regression problem results real values. Decision Trees and Linear Regression are regularly used regression algorithms and use some metrics involved in regression like mean squared error and root mean squared...

5 minutes read.

Index Error in Python

The index errors are the run time error that is raised in Python when we try to access an index that does not exist. This might seem very trivial but...

4 minutes read.

How to Convert Int to String in Python?

Every value we use or store in a variable in Python will have a specific data type. It describes the value's nature; based on that, Python will automatically assign a...

4 minutes read.

What is Sleeping Time in Python

Did you ever postpone a Python program's execution? Usually, you want your code to execute as quickly as possible. But there are times when it is in your best interests...

3 minutes read.

Create a Table Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.

How to Fix an EOF Error in Python?

Introduction An EOF (End-of-File) error occurs when a program tries to read beyond the end of a file or a stream, causing it to return an error message. It can happen...

8 minutes read.

How To Take Multiple Inputs In Python

In C language, we make use of the scanf() function to obtain the values from the user and store it in the variable. Coming to the Python language, we use the...

5 minutes read.

Add Element to Tuple in Python

Python: Popular high-level, all-purpose programming language Python. The new version of the Python programming language, Python 3, is used for all software applications, including web development. Python is the best programming...

4 minutes read.

Is Python Case-sensitive when Dealing with Identifiers

Yes, Python is a case-sensitive language while dealing with identifiers. Python is one of the top trending, widely-used programming languages. Python is a general-purpose programming language. It is a case-sensitive...

6 minutes read.

Python: SetBitmap() function in wxPython

SetBitmap() function In the last tutorial, we have discussed about the GetLabelText() function of wx.MenuItem class which is one of the important function of this class. Now, in this tutorial, we...

6 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.

How to Install Matplotlib in Python?

How to Install Matplotlib in Python The speed at which the enormous amount of data is generating has become a huge aid in understanding what's going on currently in the market....

4 minutes read.

Python Modulo

For basic calculations, Python provides operators. Python supports a broad range of Arithmetic Operators to do arithmetic, as given below: +Addition*Multiplication-Subtraction/Division//Floor division**Exponentiation%Remainder/Modulus As you can see, one of these basic arithmetic operators...

8 minutes read.

Python Network Programming

In network programming, python plays a very important role. Python provides full support for encoding and decoding data and network protocol in its standard library. Writing a network program in...

3 minutes read.

Conditional Expressions in Python

In Python conditional expression are sometimes referred to operator called as ternary operator. Not only Python supports ternary operator but many other programming languages supports it. Ternary operator are the...

2 minutes read.

Python Slice from Last Occurrence of K

Introduction We already know that in Python, cutting produces a sub-string out of a string. The variables start, stop, and step are used to set the slicing range. When dealing on...

3 minutes read.