As requested by the company, this project was built to set up GCP's Gmail API to handle specific requests.
- Send emails using python
- Search for emails based on a text query
- Python 3.8 or higher
- Pipenv (optional, but recommended for managing dependencies)
-
Navigate to the project folder
cd GoogleAPIChallenge
-
(Optional) If you're using Pipenv, create a virtual environment and install dependencies.
make run
it will install pipenv witht the dependencies from the requirement.txt
Be sure the python virtual environment is set for this project.
For this challenge, I went for the quickstart approach (check the docs) regarding authentication, and a credential.json
has
to be set in the project's root folder; I sent the required crendentials.json
file in the email along with the test Gmail account credentials.
- Create the gmail api key and then authorize the crendentials.
- One last step here is to add a test user to the OAuth consent screen, this is because when you run the script for the first time you will need to login with the user that you will use to test the script.
Note: The email account created to set the API for this challenge is already added as a test user.
To run the application, execute the following command from the project's root:
python main.py
Also you can run the main.py file from the IDE.
Note: Check the each method's parameter active to be set to True
in order to execute sending the email or search for emails.
-
The main.py file creates the instance of the class GmailApi with the
token.json
path as a parameter -
Inside the
GmailApi
we have five methods:Constructor method
to initialize the instance's attribute created for the class.service()
Creates the service to access the Gmail API; it checks if the token.json file exists. If not, It will prompt the user to log in to the Gmail of the designated test user in the GCP console.send_email()
Taking the parameters to(receiver), from_(sender), subject, message_content, activate=True, to then send an emailsearch_emails
Takes the parameter user_id, search_query, activate=True. This will search for emails based on a given query and return the results of that search in the output, and a txt file, search operators can also be used in thesearch_query
parameter.get_messages
This helper function is used insidesearch_emails()
to handle email ids, find the message's content, and decode each one.
The challenge was based on the provided scope by the recruiter, building a script to handle sending emails and searching for emails based on a query. Something that could be implemented here is a rest API using FastApi to handle the script with HTTP requests.