Search code examples
javascriptnode.jsgmaildiscordgmail-api

How to read unread emails with the Gmail API (node)


I'm creating a bot that will take emails sent to a specific account and push them to a discord server. I found the Gmail API. How would I be able to find unread emails, and mark them as read once operated on?


Solution

  • The Gmail API does not instantly detect if a new email has arrived. However, you can trigger a script to check for unread emails from a certain sender.

    For example:

    var newEmails = Gmail.Users.Threads.list("me", {"q":"is:unread from:email"});
    //do stuff with them
    

    Then iterate through the threads and remove the unread label from them to not repeat them in the next search:

    for (var i = 0; i < newEmails.threads.length; i++){
          var threadId = newEmails.threads[i].id;
          Gmail.Users.Threads.modify({"removeLabelIds":["UNREAD"]}, "me", threadId);
        }
    

    If you are using Apps Script, create a Trigger to run the function every x minutes or hours in Edit > Current Project Triggers.

    References: