Sending emails using SMTP and MIME in Python

In this post, we’ll learn about sending attachment emails using SMTP and MIME in Python. The program will read a text file with data and send emails to the respective email addresses in the file. These emails are very similar to the machine-generated emails we receive from various sites/organizations that we have subscribed to. Sending attachment emails using SMTP and MIME in Python is done using smtplib.

Let’s get started!

We start by first importing SMTP and MIME packages. MIME is used to send non-ASCII files through SMTP.

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

Since we are trying to replicate the bulk emails sent by organizations, we will create a text file with all the details of our message receivers. We will then read this text file, and save all its details in a list.

The ‘grade.txt’ file has the content:

Snigdha abc@gmail.com 42 11 A
Ranjith def@gmail.com 34 12 B
Deepa ghi@gmail.com 24 10 A+
Vishnu jlk@gmail.com 73 10 C

fo=open("grade.txt","r")
l1=fo.readlines()
print(l1)

Output:

['Snigdha abc@gmail.com 42 11 A\n', 'Ranjith def@gmail.com 34 12 B\n', 'Deepa ghi@gmail.com 24 10 A+\n', 'Vishnu jkl@gmail.com 73 10 C\n']

Now, let’s create a 2D list with name, email, rollno, class, and grade as separate as columns and the entries as rows.

for idx,val in enumerate(l1):
    l1[idx]=val[:-1]
for idx,val in enumerate(l1):
    l1[idx]=val.split(" ")

print(l1)

Output:

[['Snigdha', 'abc@gmail.com', '42', '11', 'A'], ['Ranjith', 'def@gmail.com', '34', '12', 'B'], ['Deepa', 'ghi@gmail.com', '24', '10', 'A+'], ['Vishnu', 'jkl@gmail.com', '73', '10', 'C']]
Now we initialize the SMTP Object ‘server’ using the SMTP() function. You need to have a Gmail account for this program. The port number of SMTP is 589. Further, we’ll start the server and then log in using your email address and password.
server= smtplib.SMTP('smtp.gmail.com',port=587)
server.starttls()
server.login("<Enter_your_email_address>","<Enter_your_password>")

Now, we send an email to every person on the list. For this, first, initialize the ‘from’ address and ‘to’ address. The ‘to’ address will be the element at index 1.

for i in l1:
    fromaddr="sample@gmail.com"             #enter your email address
    toaddr=i[1]

We then create a MIMEMultipart object msg. Initialize ‘From’ section, ‘To’ section and ‘Subject’ section with the desired addresses and subjects.

'   msg=MIMEMultipart()
    msg['From']=fromaddr
    msg['To']=toaddr
    msg['Subject']="Passing Letter"

Write the body of the mail to be sent. Then the data saved in the array.

Then attach this body to the msg object.

    body="Hello {0} ,\nof class {1} , roll no.{2}\nYour grade is {3}".format(i[0],i[3],i[2],i[-1])
    msg.attach(MIMEText(body,'plain'))

We then convert the msg object to string and store it in text.

After this, send the mail using the sendmail() function which takes from address, to address and text as parameters.

    text=msg.as_string()
    server.sendmail(fromaddr,toaddr,text)

Lastly, quit the server. This logs you out from the mail server.

server.quit()

Output:

Here’s the mail received…

Whole Code:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


fo=open("grade.txt","r")
l1=fo.readlines()
print(l1)
for idx,val in enumerate(l1):
    l1[idx]=val[:-1]
for idx,val in enumerate(l1):
    l1[idx]=val.split(" ")

print(l1)

server= smtplib.SMTP('smtp.gmail.com',port=587)
server.starttls()
server.login("<Enter_your_email_address>","<Enter_your_password>")

for i in l1:
    fromaddr="sample@gmail.com"      #Enter your email address
    toaddr=i[1]

    msg=MIMEMultipart()

    msg['From']=fromaddr
    msg['To']=toaddr
    msg['Subject']="Passing Letter"

    body="Hello {0} ,\nof class {1} , roll no.{2}\nYour grade is {3}".format(i[0],i[3],i[2],i[-1])
    msg.attach(MIMEText(body,'plain'))


    text=msg.as_string()
    server.sendmail(fromaddr,toaddr,text)

server.quit()

 

Also see,

One response to “Sending emails using SMTP and MIME in Python”

  1. mike lancaster says:

    Thanks! This was very helpful. Lord willing, I will get mine working.

Leave a Reply

Your email address will not be published. Required fields are marked *