sending an email through gmail using python

How To send email using python.

Simple mail transfer protocol (SMTP) is an application layer protocol that transfers an email from one user to another user. As a software developer or programmer, we need to send lots of plain text email and also an email with reports, query results, images, text data, application form data, etc to the business client from a different platform. Downloading these things and sending them as an email through another platform is hectic and costs a lot of manual work so if we can automate this task and do it through the script it will save lots of time and cost.

Python provides a built-in library for sending an email via SMTP protocol. We can send an email using the smtplib python built-in module. No extra installation required for this we can simply use it by importing as follows.

import  smtplib

In this tutorial, we will learn the following things

  1. Configure Gmail account
  2. Sending simple text mail using smtplib
  3. Sending email with attachment using smtplib
  4. Sending email with HTML content

1.Configure Gmail account 

To send an email through Gmail in python we need to do some configuration because google does not allow us to send an email via any script without configuration. We need to turn on  Less secure app access. Click the below link to turn on the less secure app access and please make sure that you haven’t enabled two-factor authentication because you can’t turn on the less secure  app access if you have enabled two-factor authentication

https://myaccount.google.com/lesssecureapps


img: less secure app access ON/OFF in gmail

There is another way to use Gmail without turning on the less secure app access option. That is using the OAuth authentication technique for authentication which is more secure. We will write another separate blog on how to implement the Oauth2 authentication technique using a python script.

Strong recommendation: Reset the setting once the testing/task has been completed because of email security concerns.

2.Sending simple text mail using smtplib

import os
import smtplib
from getpass import getpass
#replace youremail@gmail.com with your email address
SENDER_ADDRESS='youremail@gmail.com'
EMAIL_PASSWORD=getpass("Enter Sender email  password:")
RECEIVER_ADDRESS=input("Please enter receiver email address:")
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
	smtp.starttls()
	smtp.login(SENDER_ADDRESS, EMAIL_PASSWORD)
	subject = 'Sending an email using python'
	mail_body ="""\
			Hi,
			
			This is test mail sent through a python script.
			
			Please visit thequickblog.com for more technical blogs.
			
			Thank You,
			The Quick Blog
			"""
	message = f'Subject: {subject} \n\n {mail_body}'
	smtp.sendmail(SENDER_ADDRESS,RECEIVER_ADDRESS,message)

Save the above program as tqbemail.py and execute it using the python tqbemail.py command in command prompt/terminal.


img: program execution in command prompt
img: Sent mail in sendeer side

img: Received mail at receiver inbox

3. Sending email with an attachment

import smtplib 
from email.mime.multipart import MIMEMultipart 
from email.mime.base import MIMEBase 
from email.mime.text import MIMEText 
from getpass import getpass
from email import encoders 
from_emailaddr = 'quickblognp@gmail.com'
to_emailaddr = input("Enter receiver email:")
email_password = getpass("Enter Sender email  password:")
email = MIMEMultipart() 
email['From'] = from_emailaddr 
email['To'] = to_emailaddr 
#email subject
email['Subject'] = "Sending an email with attachment using python script-Thequickblog"
#Email body
body = """\
	Hi, 
			
	This is test email with attachment using python script
			
	Please visit thequickblog.com for more technical blogs.
			
	Thank You,
	The Quick Blog
"""
#Email attachment
attachment_file = "py_tutorial.pdf"

email.attach(MIMEText(body, 'plain')) 
attachment = open(attachment_file, "rb") 
mime_base = MIMEBase('application', 'octet-stream') 
mime_base.set_payload((attachment).read()) 

# encode into base64 
encoders.encode_base64(mime_base) 
mime_base.add_header('Content-Disposition', "attachment; filename= %s" % attachment_file) 
email.attach(mime_base) 

#SMTP session and authentication  
s = smtplib.SMTP('smtp.gmail.com', 587) 
s.starttls() 
s.login(from_emailaddr, email_password) 
text = email.as_string() 

#sending the mail 
s.sendmail(from_emailaddr, to_emailaddr, text) 

s.quit() 

Save the above program as tqattachment.py and execute it using the python tqattachment.py command in command prompt/terminal.

img : program execution in command prompt
img : sent mail at sender side

4. Sending email with HTML content

import os
import smtplib
from getpass import getpass
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
SENDER_ADDRESS='quickblognp@gmail.com'
EMAIL_PASSWORD=getpass("Enter Sender email  password:")
RECEIVER_ADDRESS=input("Please enter receiver email address:")
message = MIMEMultipart('alternative')
message['Subject'] =  'Sending an email with HTML content using python -Thequick Blog'
message['From'] = SENDER_ADDRESS
message['To'] = RECEIVER_ADDRESS
mail_body ="""\
    <html>
        <head>------------The Quick Blog ---------------</head>
        <body>
            <p>Hi,<br>
            <br>
            This is test mail sent through python  script.<br>
            Please visit thequickblog.com for more technical blogs.<br>
            </p>
            <hr>
            Thank You,<br>
            The Quick Blog
            <hr>
        </body>
    </html>
 """
html_content=MIMEText(mail_body, "html")
message.attach(html_content)
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
	smtp.starttls()
	smtp.login(SENDER_ADDRESS, EMAIL_PASSWORD)
	smtp.sendmail(SENDER_ADDRESS,RECEIVER_ADDRESS,message.as_string())
	smtp.quit()

Save the above program as tqbhtmlmail.py and execute it using the python tqbhtmlmail.py command in command prompt/terminal.

img: program execution in command promt
img : Received mail at receiver inbox

Leave a Reply