Searching emails
We can also search for specific emails, in the same way we enter queries in the gmail search box. The search() function returns a list of GmailMessage objects that match the search parameter. We can also perform special search operations like:
- ‘from:sender@email.com’ : fetch emails from a particular sender
- ‘subject:Python’ : emails with a specific subject
- ‘label:UNREAD’ : unread emails
- ‘has:attachment’ : emails which contain an attachment
Example:
Python3
import ezgmail # searching for specific emails results = ezgmail.search( 'w3wiki' ) print (results[ 0 ]) # special searches results = ezgmail.search( 'has:attachment' ) print (results[ 0 ]) |
Handling mails with EZGmail module in Python
EZGmail is a Python module that can be used to send and receive emails through Gmail. It works on top of the official Gmail API. Although EZGmail does not cover everything that can be done with the Gmail API, it makes the common tasks very simple which are a lot more complicated using Google’s own API. In this article, we will take a look at how to use this module to send, search, read emails and download attachments.
Installation
This module does not comes pre-installed with Python. To install it type the below command in the terminal.
pip install EZGmail
Enabling the Gmail API
First, we need to enable the Gmail API from the official website. Go to the official google developer website https://developers.google.com/gmail/api/quickstart/python and follow the below steps.
- Click on Enable the Gmail API button.
- Select Desktop app as OAuth client.
- Next, click on Download Client Configuration button.
- A json file named ‘credentials.json‘ will be downloaded. Copy this file to the working directory of Python.
Authenticating the Application
Next we need to authorise our program to use our Google account. This authorisation process needs to be performed only once.
- Run ezgmail.init() from Python shell.
- This opens up a browser window and takes us to the authentication page. We then need to select the Google account and authorise the application to use our account.
The setup is complete. Now, we shall see how to use this module.