A simple Node.js Gmail client which checks/returns email message(s) straight from any Gmail-powered account (both private and company).
There are two main functionalities this library provides:
check_inbox(): Polls a mailbox for a given amount of time. At the end of the operation, the desired message is returned (if found).get_messages(): Can be used to perform various assertions on the email objects (see example below).
P.S, I have written a story on medium, how using Cypress, we are testing our user registration process at Tastewise.
- Node.js 22 or newer is required. Cypress runs
setupNodeEventson your system Node, so checknode -vthere too. - The full
googleapisSDK (~120 MB) was replaced by@googleapis/gmail(~1 MB), so installs are much faster. The API is unchanged and no code changes are needed. - Existing
credentials.jsonandtoken.jsonfiles keep working.
If you're stuck on Node 20 or older, pin gmail-tester@^1.5.0.
- Install using
npm:
npm install --save-dev gmail-tester
- Save the Google Cloud Platform OAuth2 Authentication file named
credentials.jsoninside an accessible directory (see instructions below). - In terminal, run the following command:
node <node_modules>/gmail-tester/init.js <path-to-credentials.json> <path-to-token.json> <target-email>
<path-to-credentials.json> Is the path to OAuth2 Authentication file.
<path-to-token.json> Is the path to OAuth2 token. If it doesn't exist, the script will create it.
[port] Optional. The local port for the OAuth redirect. Default: 32019.
The script opens your browser on Google's consent page (the link is also printed in the terminal). Select the account for <target-email> and grant permission to view your email messages. Google then redirects to http://localhost:32019, the script saves the token and exits. There is no code to copy and paste.
If the script keeps waiting after you grant permission, the redirect didn't reach it. Check that http://localhost:<port> is an authorized redirect URI for your OAuth client, and run init.js on the same machine as the browser.
When it's done, the script prints:
[gmail] Token ready at <path-to-token.json>. You're all set!
- In the Google Cloud Console, create a project or select an existing one.
- Enable the Gmail API for the project.
- Configure the consent screen in Google Auth Platform. Choose External for a personal Gmail account.
- While the app is in Testing mode, only accounts listed under Audience → Test users can sign in. Add the Gmail accounts you want to test with.
- Refresh tokens for apps in Testing mode expire after 7 days. For long-lived CI tokens, publish the app (verification isn't required for personal use).
- Create an OAuth client under Clients:
- Desktop app (recommended): works as-is. Google allows any
http://localhostport for Desktop clients. - Web application also works, but you must add
http://localhost:32019(orhttp://localhost:<your-port>) under Authorized redirect URIs.
- Desktop app (recommended): works as-is. Google allows any
- Download the client's JSON and save it as
credentials.json. Desktop clients have aninstalledkey at the top level and Web clients haveweb. Both are supported.
⛔️ Never share or commit credentials.json nor token.json!!! Whoever has it will have full access to your inbox!
credentials: Path to credentials JSON file or JSON Object.
token: Path to OAuth2 token file or JSON Object.
port: Optional. Local port for the OAuth redirect if a new token is needed. Default: 32019.
options:
from: String. Filter on the email address of the receiver.to: String. Filter on the email address of the sender.subject: String. Filter on the subject of the email.include_body: boolean. Set totrueto fetch decoded email bodies.include_attachments: boolean. Set totrueto fetch the base64-encoded email attachments.before: Date. Filter messages received before the specified date.after: Date. Filter messages received after the specified date.label: String. The default label is 'INBOX', but can be changed to 'SPAM', 'TRASH' or a custom label. For a full list of built-in labels, see https://developers.google.com/gmail/api/guides/labels?hl=en
Returns:
A promise of an array of email objects (empty if nothing matches). It rejects if Gmail can't be reached or authorization fails. Before 1.5.0 it resolved to undefined in that case.
The email objects have the following fields:
[
{
from: "Human Friendly Name <sender@email-address>",
receiver: "your@email-address",
subject: "string",
body: {
html: "string",
text: "string"
}
}
// ...
];Some senders will send you text/html content, the others will send you plain/text, and some will send you both. Make sure you are looking for the content in the right body field.
credentials: Path to credentials JSON file or JSON Object.
token: Path to OAuth2 token file or JSON Object.
port: Optional. Local port for the OAuth redirect if a new token is needed. Default: 32019.
options:
from: String. Filter on the email address of the receiver.to: String. Filter on the email address of the sender.subject: String. Filter on the subject of the email.include_body: boolean. Set totrueto fetch decoded email bodies.include_attachments: boolean. Set totrueto fetch the base64-encoded email attachments.before: Date. Filter messages received before the specified date.after: Date. Filter messages received after the specified date.wait_time_sec: Integer. Interval between inbox checks (in seconds). Default: 30 seconds.max_wait_time_sec: Integer. Maximum wait time (in seconds). When reached and the email was not found, the script exits. Default: 30 seconds.label: String. The default label is 'INBOX', but can be changed to 'SPAM', 'TRASH' or a custom label. For a full list of built-in labels, see https://developers.google.com/gmail/api/guides/labels?hl=en
Returns:
An array of email objects with the following fields:
[
{
from: "Human Friendly Name <sender@email-address>",
receiver: "your@email-address",
subject: "string",
body: {
html: "string",
text: "string"
}
}
// ...
];In addition, verbose messages will be written to console.
credentials: Path to credentials JSON file or JSON Object.
token: Path to OAuth2 token file or JSON Object.
Refresh the access token. A new file will overwrite the existing one in token_path.
const path = require("path");
const gmail = require("gmail-tester");
const email = await gmail.check_inbox(
path.resolve(__dirname, "credentials.json"), // Assuming credentials.json is in the current directory.
path.resolve(__dirname, "gmail_token.json"), // Look for gmail_token.json in the current directory (if it doesn't exists, it will be created by the script).
{
subject: "Activate Your Account", // We are looking for 'Activate Your Account' in the subject of the message.
from: "no-reply@domain.com", // We are looking for a sender header which is 'no-reply@domain.com'.
to: "<target-email>", // Which inbox to poll. credentials.json should contain the credentials to it.
wait_time_sec: 10, // Poll interval (in seconds).
max_wait_time_sec: 30, // Maximum poll time (in seconds), after which we'll giveup.
include_body: true
}
);
if (email) {
console.log("Email was found!");
} else {
console.log("Email was not found!");
}const { defineConfig } = require("cypress");
const gmailTester = require("gmail-tester");
const path = require("path");
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
on("task", {
"gmail:get-messages": async (args) => {
const messages = await gmailTester.get_messages(
path.resolve(__dirname, "credentials.json"),
path.resolve(__dirname, "token.json"),
args.options
);
return messages;
},
});
},
},
});/// <reference types="Cypress" />
describe("Email assertion:", () => {
it("Using gmail_tester.get_messages(), look for an email with specific subject and link in email body", function () {
// debugger; //Uncomment for debugger to work...
cy.task("gmail:get-messages", {
options: {
from: "AccountSupport@ubi.com",
subject: "Ubisoft Password Change Request",
include_body: true,
before: new Date(2019, 8, 24, 12, 31, 13), // Before September 24rd, 2019 12:31:13
after: new Date(2019, 7, 23), // After August 23, 2019
},
}).then((emails) => {
assert.isAtLeast(
emails.length,
1,
"Expected to find at least one email, but none were found!"
);
const body = emails[0].body.html;
assert.isTrue(
body.indexOf(
"https://account-uplay.ubi.com/en-GB/action/change-password?genomeid="
) >= 0,
"Found reset link!"
);
});
});
});Please feel free to contribute to this project.
- Built using googleapis.
