How to delete emails with the Gmail API and Ruby

7 min read

Getting your inbox to Inbox Zero, is something that most people want to do, although that’s not easy to accomplish most of the time, as we might need to delete multiple emails multiple times per day. Gladly, with the help of the Nylas Email API and Ruby, we can build a project to help reach that goal faster by providing email deletion.

Is your system ready?

If you already have the Nylas Ruby SDK installed and your Python environment configured, continue with the blog.

Otherwise, I recommend reading the post How to Send Emails with the Nylas Ruby SDK where the basic setup is clearly explained.

What are we going to talk about?

What our application will look like

Our application starts with a screen displaying some parameters that we have to filter our email inbox. We can specify the email status, who sent the emails, what’s the subject and the emails that were sent after a certain date:

Delete Emails with Ruby

Once we specify a couple of parameters, we’re going to get how many emails satisfy the conditions:

Delete Emails with Ruby with parameters

Here we have only one email that we can delete. If we had 20 or 50 more emails, we could also choose to delete them all.

Confirm deletion

Once the email or emails have been deleted, passing the same parameters will return zero emails.

No more emails

By the way, the Nylas Email API request endpoint has a hard limit of one hundred emails per request.

Installing the Sinatra package

As we want to create a Flask web application, our best option is to use Sinatra, one of the most popular Micro Frameworks in the Python world:

$ gem install sinatra
$ gem install webrick

Once installed, we’re ready to go.

Creating the project

Let’s see how we can delete our Gmail emails using Ruby.

First, we’re going to create a folder called Delete_Gmail, and inside, we’re going to create a folder called views.

Create a file called delete_gmail.rb with the following source code:

# frozen_string_literal: true

# Import your dependencies
require 'sinatra'
require 'dotenv/load'
require 'nylas'

# Use sessions
enable :sessions

# Initialize your Nylas API client
nylas = Nylas::API.new(
  app_id: ENV['CLIENT_ID'],
  app_secret: ENV['CLIENT_SECRET'],
  access_token: ENV['ACCESS_TOKEN']
)

# Main page with form
get '/' do
    # Create a hash to store labels information
    labelsDict = Hash.new
    # Get all labels
    labels = nylas.labels
    # Clear the emails session variable
    session[:emails] = []
    # Loop labels and assign them to the hash
    for label in labels
		labelsDict[label.name] = label.id
	end
	# Store the "trash" id on the trash session variable
	session[:trash] = labelsDict["trash"]
	# Call our main page
    erb :main, layout: :layout
end

post '/' do
    # When we press submit, get all the parameters
    # Create a string with all the parameters
    # that are not empty
    query = "in: inbox; unread: " + params[:read_unread] + ";"
    if params[:from] != ""
        query = query + " from: " + params[:from] + ";"
    end
    if params[:subject] != ""
        query = query + " subject: " + params[:subject] + ";"
    end
    if params[:received] != ""
        qYear = Date.strptime(params[:received],'%Y-%m-%d').strftime('%Y')
        qMonth = Date.strptime(params[:received],'%Y-%m-%d').strftime('%m')
        qDay = Date.strptime(params[:received],'%Y-%m-%d').strftime('%d')
        uDate = Time.local(qYear, qMonth, qDay, 0, 0,0).strftime("%s") 
        query = query + " received_after: " + uDate + ";"
    end
    query = query.chomp(";")
    # Here we grab the params string and turn it into a hash format
    pairs = query.split(/[:;]/).map(&:strip).each_slice(2).map { |k,v| [k.strip.to_sym, v.strip] }
    # Make it a hash
    result = Hash[pairs]
    # Call the messages endpoint with the params hash
    emails = nylas.messages.where(result)
    emails_array = []
    email_titles = []
    for email in emails
        # Store the email id and email subject
        emails_array.push(email.id)
        email_titles.push(email.subject)
    end
    # Fill emails session variables with the array of emails
    session[:emails] = emails_array
    # Call the filtered page passing the number of emails and the titles
    erb :filtered, layout: :layout, locals: { count: emails_array.length(), titles: email_titles}
end

# When we press the delete button
post '/delete' do
    # Get the emails from the session variable
    emails_array = session[:emails]
    # Clean the emails session variable
    session[:emails] = []
    # For each email
    for email in emails_array
        # Get the email information based on the id
        message = nylas.messages.find(email)
        # Update the label of the email
        message.update(label_ids: [session[:trash]])
        # Save the email
        message.save
    end
    # Go back to the main page
    redirect "/"
end

Inside the views folder, we need to create three different files. Let’s start with layout.erb:

<html>
<head>
<script src="https://cdn.tailwindcss.com"></script>
<title>Delete Gmail Emails</title>
</head>
<body>
<%= yield %>
</body>
</html>

Then main.erb:

<div class="bg-[#315acb] border-green-600 border-b p-4 m-4 rounded grid place-items-center">
<p class="text-4xl">Gmail Deleter</p>
<form method="post">
<br>
<table>
<tr>
<td><p class="font-bold">Email Status:</p></td>
<td><input type="radio" id="read" name="read_unread" value="false" checked>
<label for="read" class="font-bold">read emails</label><br>
<input type="radio" id="unread" name="read_unread" value="true">
<label for="unread" class="font-bold">unread emails</label><br></td>
</tr>
<tr><td><br></td></tr>
<tr>
<td><label for="from" class="font-bold">From: </label></td>
<td><input type="text" name="from" value="" ></input></td>
</tr>
<tr>
<td><label for="subject" class="font-bold">Subject: </label></td>
<td><input type="text" name="subject" value="" ></input></td>
</tr>
<tr>
<td><label for="received" class="font-bold">Received after: </label></td>
<td><input type="date" id="received" name="received" min="2018-01-01" max="2025-01-01"></td>
</tr>
</table>
<br>
<button type="submit" class="block bg-blue-500 hover:bg-blue-700 text-white text-lg mx-auto py-2 px-4 rounded-full">Submit</button>
</form>
</div>

Finally, filtered.erb:

<div class="bg-[#315acb] border-green-600 border-b p-4 m-4 rounded grid place-items-center">
<p class="font-bold">There are <%= count %> email(s). Would you like to delete them?</p><br>
<p>
<% titles.each do |title| %>
   <%= title %><br>
<%end %>
</p>
<br>
<form method="post" action="/delete">
<button type="submit" class="block bg-blue-500 hover:bg-blue-700 text-white text-lg mx-auto py-2 px-4 rounded-full">Delete</button>
</form>
<button class="block bg-blue-500 hover:bg-blue-700 text-white text-lg mx-auto py-2 px-4 rounded-full" onclick="window.location.href='/';">
      Cancel
    </button>
</div>

And that’s it. We’re ready to roll.

Running our Gmail Delete application

To run our application to delete emails from our Gmail inbox, we just need to type the following on the terminal window:

$ ruby delete_gmail.rb
Gmail delete application running

Our application will be running on port 4567 of localhost, so we just need to open our favourite browser and go to the following address:

http://localhost:4567

Now we can easily delete our Gmail emails using Ruby.

What’s next?

You can sign up Nylas for free and start building!

If you want to learn more about Emails, go to our documentation. Also, don’t miss the action. Join our LiveStream Coding with Nylas:

Related resources

How to create and read Google Webhooks using Ruby

Create and read your Google webhooks using Ruby and Sinatra, and publish them using Koyeb. Here’s the full guide.

Build mail merge and email templates using TinyMCE Rich Text Editor

Learn how to build Mail Merge and Email Template functionality in your email workflow using TinyMCE Rich Text Editor.

Send emails using TinyMCE Rich Text Editor

Learn how to improve your email workflow using TinyMCE Rich Text Editor.