Thursday, 26 December 2019

Sending Email from Gmail account using Python


In this blog, we will see how we can send email with attachments using Python. To send mail, we do not need any external library. There is a module called SMTPlib, which comes with Python. It uses SMTP (Simple Mail Transfer Protocol) to send the mail. It creates SMTP client session objects for mailing. SMTP needs valid source and destination email ids, and port numbers. The port number varies for different sites. As an example, for google the port is 587.
At first we need to import the module to send mail.
import smtplib
Here we are also using the MIME (Multipurpose Internet Mail Extension) module to make it more flexible. Using MIME header, we can store the sender and receiver information and some other details. We are using Google's Gmail service to send mail. So we need some settings (if required) for google's security purposes. If those settings are not set up, then the following code may not work, if the google does not support the access from third-party app.
To allow the access, we need to set 'Less Secure App Access' settings in the google account. If the two step verification is on, we cannot use the less secure access.
To complete this setup, go to the Google's Admin Console, and search for the Less Secure App setup.

Steps to Send Mail with attachments using SMTP (smtplib)

  • Create MIME
  • Add sender, receiver address into the MIME
  • Add the mail title into the MIME
  • Attach the body into the MIME
  • Start the SMTP session with valid port number with proper security features.
  • Login to the system.
  • Send mail and exit

Create config file
#config.json file name
{
  "params":
 {
  "sender-email":"sender-email@gmail.com",
  "gmail-password":"gmail-password",
   "receiver-email": "receiver-email@gmail.com"
 }
}

Code Example(create main.py file and paste below code)
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import json

#accessing value from config file
with open('config.json','r') as c:
params = json.load(c)["params"]
#The mail addresses and password from config.json(configuration file)
sender_address = params['sender-email']
sender_pass = params['gmail-password']
receiver_address = params['receiver-email']
#Setup the MIME
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'Python code test email.'   #The subject line
#The body and the attachments for the mail
#message.attach(MIMEText(mail_content, 'plain'))
#text = """ Hi, This is a simple mail. There is text as well as attachments are there The mail is sent using Python SMTP library. Thank You!"""

# write the HTML part
html = """ <html> <body> <p>Hi,<br> This is a simple mail.</p> <p>\
<a href="https://www.google.co.in">There is text as well as attachments are there The mail is sent using Python SMTP library. Thank You!</p> <p> Feel free to <strong>let us</strong> know what content would be useful for you!</p> </body> </html> """


filename = "C:\\Users\\DP\\Payments, refunds and deposits - Blueprint OMS user guide - Confluence.pdf"
flname1 = filename.split("\\")
flname = filename.split("\\")[(len(flname1)-1)]
#print(len(flname1))
# Open PDF file in binary mode
# We assume that the file is in the directory where you run your Python script from
with open(filename, "rb") as attachment:
# The content type "application/octet-stream" means that a MIME attachment is a binary file
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
# Encode to base64
encoders.encode_base64(part)
# Add header
part.add_header("Content-Disposition", f"attachment; filename= {flname}")
# Add attachment to your message and convert it to string
message.attach(part)


# convert both parts to MIMEText objects and add them to the MIMEMultipart message
#part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
#message.attach(part1)
message.attach(part2)
#Create SMTP session for sending the mail
session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port
session.starttls() #enable security
session.login(sender_address, sender_pass) #login with mail_id and password
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()
print('Email sent successfully')

Output:
Email sent successfully

No comments:

Post a Comment

Python Datatype Interview Questions

Q)  What is Python? Python is a high-level, interpreted, interactive, and object-oriented scripting language. Python is designed to be...