Optimizing Gmail API Query or Alternative Method to Retrieve Total Email Size

29 views Asked by At

I'm currently working on a project that involves calculating the total size of emails in a Gmail account. However, the process of fetching and calculating the size of each individual email is taking too long, ranging from 3 to 5 minutes depending on the account and the number of emails. This delay is not feasible for the functionality I'm aiming for on my site.

I'm using the Gmail API and my current approach involves fetching all the emails and then calculating the size of each one individually. I'm aware that this method might not be the most efficient, and I'm looking for suggestions on how to optimize the API query or if there's an alternative method to retrieve the total size of emails in a Gmail account.

Here is my current Node.js code.

async function calculateTotalSize(auth) {
  const gmail = google.gmail({ version: "v1", auth });
  let nextPageToken;
  let totalMessages = 0;
  let totalSize = 0;
  let pageCount = 0;

  do {
    const res = await gmail.users.messages.list({
      userId: "me",
      maxResults: 100,
      pageToken: nextPageToken,
      fields: "nextPageToken,messages(id,sizeEstimate)",
    });

    const messages = res.data.messages;
    if (!messages || messages.length === 0) {
      console.log("No messages found.");
      return;
    }

    console.log(messages.length);

    for (const message of messages) {
      const messageInfo = await gmail.users.messages.get({
        userId: "me",
        id: message.id,
      });
      totalSize += messageInfo.data.sizeEstimate;
      console.log("- Total size of message:", totalSize, "bytes");
    }

    nextPageToken = res.data.nextPageToken;
    pageCount++;
  } while (nextPageToken);
}

authorize().then(calculateTotalSize).catch(console.error);

Any insights or suggestions would be greatly appreciated

I expected to find a faster and more efficient way to obtain this information, either by optimizing the API query or by finding an alternative method to retrieve the total email size.

0

There are 0 answers