Sending emails via python

ACES PVGCOET
1 Hour Blog Series
Published in
4 min readJan 24, 2021

Sending Emails — A brief overview

Usually, the task of sending emails is done using the MTP (Mail Transfer Protocol). In the present day, there is a separate protocol called SMTP (Simple Mail Transfer Protocol) which is the widely used protocol for sending emails.

This protocol works on a client-server basis, similar to any other. When we want to send an email to a target machine, we (the client) need to send the mail contents to the SMTP Server. The server will now route it to the desired target machine.

Prerequisite Setup for Sending Emails with Python

Before going through the rest of this tutorial, I’d advice you to set up a dummy gmail account that you can use to test sending emails.After setting up the account, there’s one more thing you need to do.

By default, your Gmail account is not configured to allow access from less secure applications such as SMTP. We need to enable this access for our account.

You can go to your gmail account configuration page and enable access from your Google account.

Less secure app access

Send Emails using Python SMTP

Python has an SMTP client library (smtplib), which it will use to send emails to an SMTP server (Gmail).

This is a part of the standard library, so you can directly import it!

Okay, so now let’s try writing a script to send a test email.

import smtplib

Any email using SMTP must have the following contents:

  • The Sender address
  • The receiver address
  • A subject (Optional)
  • The body of the mail

Let’s write all of them down.

import smtplibsender_address = "sender@gmail.com" # Replace this with your Gmail addressreceiver_address = "receiver@gmail.com" # Replace this with any valid email addressaccount_password = "xxxxxxxxxx" # Replace this with your Gmail account passwordsubject = "Test Email using Python"body = "Hello from AskPython!\n\nHappy to hear from you!\nWith regards,\n\tDeveloper"# Endpoint for the SMTP Gmail server (Don't change this!)smtp_server = smtplib.SMTP_SSL("smtp.gmail.com", 465)# Login with your Gmail account using SMTPsmtp_server.login(sender_address, account_password)# Let's combine the subject and the body onto a single messagemessage = f"Subject: {subject}\n\n{body}"# We'll be sending this message in the above format (Subject:...\n\nBody)smtp_server.sendmail(sender_address, receiver_address, message)# Close our endpointsmtp_server.close()

Make sure you replace the sender_address, receiver_address and account_password with your Gmail account information!

What we’re doing is that we use the SMTP Server to access our Gmail account, using a Secure SMTP (SMTP_SSL). After we login, we can send the message to the receiver directly, using smtp_server.sendmail()!

Now, if you enter the same account for the sender and receiver, you’ll get an email similar to mine.

Let’s check the contents.

Indeed, we’ve just sent a proper email using Python!

ADDING ATTACHMENTS USING PYTHON

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. MIME is also needed to set the attachment with the mail.

Steps to Send Mail with attachments using SMTP (smtplib)

  • Create MIME
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
  • Add sender, receiver address into the MIME
#The mail addresses and password
sender_address = 'sender123@gmail.com'
sender_pass = 'xxxxxxxx'
receiver_address = 'receiver567@gmail.com'
  • Add the mail title into the MIME
#Setup the MIME
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'A test mail sent by Python. It has an attachment.'
  • Attach the body into the MIME
#The body and the attachments for the mail
mail_content = '''Hello,
This is a test mail.
In this mail we are sending some attachments.
The mail is sent using Python SMTP library.
Thank You
'''
message.attach(MIMEText(mail_content, 'plain'))
  • Open the file as binary mode, which is going to be attached with the mail
attach_file_name = 'TP_python_prev.pdf'
attach_file = open(attach_file_name, 'rb') # Open the file as binary mode
  • Read the byte stream and encode the attachment using base64 encoding scheme.
payload = MIMEBase('application', 'octate-stream')
payload.set_payload((attach_file).read())
encoders.encode_base64(payload) #encode the attachment
  • Add header for the attachments
#add payload header with filename
payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name)
message.attach(payload)
  • Start the SMTP session with valid port number with proper security features.
#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()
  • Login to the system.
  • Send mail and exit
session.sendmail(sender_address, receiver_address, text)
session.quit()
print('Mail Sent')

Output

D:\Python TP\Python 450\linux>python 327.Send_Mail.py
Mail Sent
Mail with an attachment via python

You can refer the code on https://github.com/acespvgcoet/Sending-emails-via-python.git

Contributed by Pradnya Gaikwad.

LinkedIn Profile https://www.linkedin.com/in/pradnya-gaikwad-28b760175/

--

--