In this article, we will see how to read, send and delete emails using Python. The topics we are covering in this article are given below:

  • How to read email using Python.
  • How to send email using Python.
  • How to delete email using Python.

To do all the above steps, we’ll need 3 modules:

  • easyimap
  • smtp
  • imap

How to read email using Python

Prerequisites:

  • Python library called easyimap.
  • A Gmail username and password.

Step -1: Installing the required module

First, we need to install a library called easyimap in Python, you can also use a library called IMAP but it’s a very long process and quite hard so, in this step, we are going to use easyimap it easy and short for installing easyimap run the below command in your terminal:

pip3 install easyimap

Step -2: Importing the module

import easyimap as e

Step -3: Credentials setup

Now let’s declare the variables for an email id and for a password:

user="[email protected]"
password="your password"

Step -4: Making connection

Next, we have to create an object for connecting to the IMAP server where we have to mention which server to connect here we are connecting to the Gmail server:

server=e.connect("imap.gmail.com",user,password)

Step -5: Reading emails

So the next thing we are going to do is use a method called server.listids so what does this method does, it returns the IDs of the email in our inbox which is unread. Then we are going to create a variable for getting the context from the email and we can also choose the specific number of the email in this process we are going to fetch the context of the first email.

Finally, we can see the context of the email by running the print command, there are various types of context we can print for example. At last, we have to terminate the session between the client and SMTP server:

server.listids()
email=server.mail(server.listids()[3])
#for title
print(email.title)
#for the sender’s email address
print(email.from_addr)
#for the main content of the email
print(email.body)
#for any type of attachment with its extension
print(email.attachments)
server.quit

Here’s the complete code that you can use to read emails:

import easyimap as e

user="[email protected]"
password="wonderfun@123"

server=e.connect("imap.gmail.com",user,password)

server.listids()

email=server.mail(server.listids()[3])

#for title
print(email.title)
#for the sender’s email address
print(email.from_addr)
#for the main content of the email
print(email.body)
#for any type of attachment
print(email.attachments)

server.quit()

Sample Output:

hello sample
Vyom <[email protected]>
hello my name is python and today I am gonna show you how to read, send and
delete emails using python

[]

Process finished with exit code 0

As you can see that all the content of the mail is printed you can easily read them in the place of attachment place is empty because there was no attachment in the email. If your email has an attachment then it shows as the name of the attachment with its extension.

How to send emails using Python

Step -1: Applying the required permissions

We are using Gmail in this tutorial so go to your email/Gmail account then go to manage your account then security and turn on the less secure app access. We have to simply import an SMTP library called ‘smtplib’.

Now, ee have to create a variable called server in which we have SMPT  SSL, SMPT server address, and SMTP  number you can check all of this in your email setting we are using Gmail here so according to Gmail we will use these

import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)

Step -2: Connecting to the SMTP server

Then we have to start the TlS for security:

server.starttls()
server.login("[email protected]", "your password")

Step -3: Framing the message

Now we have to create a variable called message and write the message:

message = "hello, how are you"

Step -4: Sending the email and disconnecting from the SMTP server

After that we use .sendmail to send an email for that we have to provide the sender’s email address and the receiver’s email address:

server.sendmail("sender’s email", "reciver’s email", message)
server.quit

Here’s the complete code that you can use to send the emails:

#import the smtplib library
import smtplib

# creating SMTP server
server = smtplib.SMTP('smtp.gmail.com', 587)

# starting TLS for security
server.starttls()

# for Authentication
server.login("[email protected]", "wonderfun@123")

# write a message
message = "hello, how are you"

# sending the email
server.sendmail("[email protected]", "[email protected]", message)

print("Successfully sent email")
# terminate the session
server.quit

Sample Output:

Successfully sent email

How to delete email using Python

Step -1: Importing the required library

import imaplib
email="[email protected]"
passw="your password"

Step -2: Connecting the server

imapserver = "imap.gmail.com"
def deleteEmailIMAP(user, password, IMAP):
   mail = imaplib.IMAP4_SSL(IMAP)
   #authentication
   mail.login(user, password)

Step -3: Select the mailbox you want to delete

mail.select("inbox")
typ, data = mail.search(None, 'SUBJECT "hello"') #Filter by subject
typ, data = mail.search(None, 'FROM "[email protected]"') #Filter by sender
typ, data = mail.search(None, 'SINCE "015-JUN-2020"') #Filter by date
typ, data = mail.search(None, "ALL") #Filter by all

Step -4: Converting the mail into specific ids and deleting the selected mail

mail.store(num, '+FLAGS', r'(\Deleted)')
   print("Successfully deleted email")

#parmanently deleting the mails that are selected
mail.expunge()
    mail.close()
    mail.logout()

Here’s the complete code that you can use to delete an email:

# import the library
import imaplib

# input your email address
email = "[email protected]"
# input your email password
passw = "wonderfun@123"
#create a imap server
imapserver = "imap.gmail.com"

def deleteEmailIMAP(user, password, IMAP):
   mail = imaplib.IMAP4_SSL(IMAP)
   #authentication
   mail.login(user, password)
   #select the mailbox you want to delete
   mail.select("inbox")
   #you can specify which email you want to delete
   typ, data = mail.search(None, 'ALL')
   #converting the messeges into specific ids
   for num in data[0].split():
       #deleting the mails
       mail.store(num, '+FLAGS', r'(\Deleted)')
   print("Successfully deleted email")
   #parmanently deleting the mails that are selected
   mail.expunge()
   #closing the mailbox
   mail.close()
   #loging out form the mail id
   mail.logout()

Final Words

In this article, we learn how to read, send and delete emails using Python and its modules.

Let us know if you guys have any questions/comments regarding the complete process.
Happy coding!

Here are some useful tutorials that you can read: