Automate Gmail With Rowy (2023): Send, Read, Reply, And More

Gmail is the most popular email service in the world with over 1.8 billion users―a third of the email client market share! And yet, few leverage its API to make the most of it whether it's at work or using a personal account.

In this article, we'll show you how to use Rowy and the Gmail API to automate your email workflow. We'll cover how to send and read emails, as well as how to automate your email replies using GPT 3.

Limitations

However you use Gmail, you are limited by its user interface's features. Learning to use the Google Gmail API opens you up to unlimited possibilities to combine Gmail with thousands of third-party tools or integrate your own custom code to automate your workflows.

You can for example have a software program to parse your emails and categorize them into meaningful labels automatically, or have an AI service draft email replies in seconds for you as we'll see in the next sections.

The average employee gets around 121 emails per day! That's a huge time sink if not managed properly, but 49% of surveyed US employees check their email every few hours. With the right know-how, we hope this article will help you reduce time spent in your inbox via automation to do something more meaningful and dear to you instead.

1. Enable The Gmail API In Google Cloud

Once you create a new Rowy project, you need to activate the Gmail API in your Google Cloud console.

Rowy is a Firebase CMS, so it integrates Google Cloud Functions out-of-the-box and you don't need to worry about setting up OAuth2. Rowy creates service accounts to authenticate you with any Google API client in just a few lines of code:

const gmail = require('@googleapis/gmail')

const gauth = new gmail.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/gmail']
});

const authClient = await gauth.getClient();

const client = await gmail.gmail({
    version: 'v1',
    auth: authClient
});

First, we create a new Google Auth client with the Gmail scope. Then, we use the Google Auth client to create a new Gmail API client. That's it! We can then use the Gmail API client to send, read, and reply to emails.

Since Firebase Auth is built on top of Google Auth, you can use the same authentication method to access any Google API client.

2. Read Emails

You can use the Gmail API to read emails from your inbox:

const res = await client.users.messages.list({
    userId: 'me',
});

const messages = res.data.messages;

The default userId is 'me', which means the authenticated service account. You can also use read emails from other users' inboxes by specifying their email address as the userId.

If the email address doesn't belong to your workspace, you'll need to implement the worflow to connect the Gmail account to your frontend app first. Since this is a bit out of scope for this article, we encourage you to have a look at the official documentation to fit your use case.

You can run scripts with Rowy using Action or Derivative columns, or webhooks. These are all Firebase cloud functions under the hood.

Actions are displayed like standard buttons, while derivate columns automatically run whenever an associated column is modified. Webhooks can be triggered via HTTP request. For example, here is an Action column that runs the aforementioned code to read emails:

0.webp

Similarly, you can use any of those Rowy features to categorize emails, send replies, or anything you can imagine with Gmail's API.

3. Categorize Emails

Similar to how you can read emails, you can also list all the email labels in your inbox:

const res = await client.users.labels.list({
    userId: 'me',
});

const labels = res.data.labels;

This is useful to classify your emails in buckets. For example, you can create a label called 'Client 1' and move all emails related to 'Client 1' to that label.

Combined with a tool like OpenAI's GPT-3, you can also use the Gmail API to automatically classify your emails. For example, you can use GPT-3 to label a new email from the available label list:

const response = await fetch("https://api.openai.com/v1/completions", {
    method: 'POST',
    headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${rowy.secrets.OPENAI_API_KEY}`
    },
    body: JSON.stringify({
        model: "text-davinci-003",
        prompt: `Using the following labels: ${row.labels.join(', ')}. Categorize the following email using exactly one label: ${row.message}`,
        temperature: 0.7,
        max_tokens: 256,
        top_p: 1,
        frequency_penalty: 0,
        presence_penalty: 0
    }),
}).then(res => res.json())

You can then use the label returned by GPT-3 to move the email to the appropriate label with Gmail's users.messages.modify method.

4. Send Emails

Of course, there is also a method to send emails. But note Gmail's API isn't suitable for massive email campaigns. For this, prefer a tool like Sendgrid.

To use it, you'll need 4 columns in your Rowy table: from to specify the sender email, to to define who to send the email to, title for the subject line, and message for the actual email content. Then, simply use the users.messages.send method:

await client.users.messages.send({
    userId: 'me',
    requestBody: {
        payload: {
            headers: [
                {
                    name: 'From',
                    value: row.from
                },
                {
                    name: 'To',
                    value: row.to,
                },
                {
                    name: 'Subject',
                    value: row.title,
                },
            ],
            body: {
                data: row.message,
                mimeType: 'text/plain',
            }
        }
    },
});

Note that you can use plain text or html for the email content. To learn more about constructing complex emails using HTML, you can check out our article on sending emails with Sendgrid.

5. Reply To Incoming Emails

Last but not least, reply to incoming emails. To do so, you'll need to use the users.messages.send method again, but with a few extra headers:

headers: [
    {
        name: 'In-Reply-To',
        value: row.parentMessageId,
    },
    {
        name: 'References',
        value: row.parentMessageId,
    },
    {
        name: "Message-ID", 
        value: row.parentMessageId
    }
    ...
]

The parentMessageId variable is the ID of the email you want to reply to. You can get it from the email list using the id property of each individual Message object.

To gain some time, you can ask GPT-3 to generate a reply for you. You just need an appropriate prompt to match your personal brand:

{
    ...
    prompt: `Write an ${row.emotion||'angry'||'excited'} reply to the following email message: ${row.message}`
}

Instead of sending the email directly, you should save the reply as a draft to be reviewed by a human beforehand:

await client.users.drafts.create({
    userId: 'me',
    requestBody: {
        message: {
          ...
        }
    }
})

Join Rowy On Discord

And voilà! You now know how to use the Gmail API with Rowy to read, send, and label emails programmatically. If you liked this Google API tutorial, you might want to learn how to use the APIs of Google Calendar, Google Sheets, or Google Docs.

If you find any issue with this article, or if you have any question, feel free to join our Discord server to talk with us. We are a friendly group of makers who love to tinker with APIs.

Get started with Rowy in minutes

Continue reading

Browse all