Firebase NodeJS Fetch emails from gmail

Viewed 35

We have a Flutter project with Firebase setup we would like to create a Firebase cloud function with nodejs that perform the following:

Listen to pop3 or IMAP email inbox hosted by Gmail, then create a new Firestore document every time a new email comes, this document should be referred to an order number or to an existing ticket The process is:

  1. Listen to an email inbox
  2. Check the subject if related to order the subject should contain the order id If order I’d not exist then check existing tickets subject if the email subject match an existing ticket title
  3. create document with referred order id or ticket id
  4. send FCM and email notification
1 Answers

The best way IMHO would be to use the server push notifications provided by the Gmail API:

The Gmail API provides server push notifications that let you watch for changes to Gmail mailboxes. You can use this feature to improve the performance of your application. It allows you to eliminate the extra network and compute costs involved with polling resources to determine if they have changed. Whenever a mailbox changes, the Gmail API notifies your backend server application.

As you will read, the Gmail API uses the Cloud Pub/Sub API to deliver push notifications, so it will be very easy to trigger a Cloud Function when a new Pub/Sub message is sent to a specific topic. As explained in the doc, upon receiving a notification you'll have to call the Gmail API with the history.list() method to get the details of the message.

So, with the above, you have a solution for points #1 and #2 of your question.

For points #3 and #4, it's just a matter of writing to Firestore and seding a FCM message from the Cloud Function. You need to use the correct Admin SDKs and you'll find a lot of examples on SO. See also the answer to your other question.

Related