0

I have a GCP Pub/Sub subscription and topic to receive notifications from my gmail inbox. It does indeed work and I get a message on my server when a new email arrives. The problem is that I want to get more information, such as the subject, and the content of the email. But I don't know how to do it, if I try to use:

google.gmail("v1").users.messages.get({ id: message.id, userId: 'me', format: 'full' });

But I get error 404

function listenForMessages() {
  const pubSubClient = new PubSub();
  try {
    const subscription = pubSubClient.subscription("mysub_",);


    let messageCount = 0;
    const messageHandler = async message => {
      console.log(`Received message ${message.id}:`);
      console.log(`\tData: ${message.data}`);
     
      const m = await google.gmail("v1").users.messages.get({ id: message.id, userId: 'me', format: 'full' });
      
      console.log(m)

      messageCount += 1;
      message.ack();
    };


    subscription.on('message', messageHandler);

    setTimeout(() => {
      subscription.removeListener('message', messageHandler);
      console.log(`${messageCount} message(s) received.`);
    }, timeout * 1000);

  } catch (error) {
    console.log("MY ERROR", error)
  }
}

const watchUserGmail = async () => {
  const request = {
    'labelIds': ['INBOX'],
    'topicName': 'mytopic_',
  }
  
  google.gmail("v1").users.watch({ userId: 'me', requestBody: request })
    .then((res) => res)
    .catch((err) => err)

}

How can I bring that extra information into the message I get from Pub/Sub?

danielm2402
  • 750
  • 4
  • 14
  • Does this [thread 1](https://stackoverflow.com/questions/61108037/) and [thread 2](https://stackoverflow.com/questions/63722052/) solve your problem? – kiran mathew Feb 10 '23 at 11:50

1 Answers1

0

PubSub will notify a Cloud Function that an email has arrived. Your Cloud Function will then need to List the emails in the folder with gmail.users.messages.list and then Get the contents of each email with gmail.users.messages.get. PubSub event data will not have email content.

Here is an example:

async function getMessages(auth) {

  const gmail = google.gmail({version: 'v1', auth});
  const res = await gmail.users.messages.list ({
      userId: 'foo@bar.com',
      labelIds: ['Label_99999'], 
  });

  const messages = res.data.messages || [];

  if (messages.length > 0) {
    for (var message of messages) {
    const msg = await gmail.users.messages.get ({
      userId: 'foo@bar.com',
      id: message.id,
      format: 'full'
    });

    let msgSubject = '';
    const msgHeaders = msg.data.payload.headers;
    for (var header of msgHeaders) {
      if (header.name === 'Subject') {
        msgSubject = header.value;
      }
    }

    const msgData = msg.data.payload.parts[0].body.data  
    const decoded = await decodeBase64(msgData);
    const msgSnippet = msg.data.snippet || '';
    const msgId = msg.data.id || '';

    } 
  }
}

async function decodeBase64(data) {
  const buff = Buffer.from(data, 'base64');  
  const text = buff.toString('utf-8');
  return text;
}

Your watcher should include a parameter to the topic which is firing the Cloud Function:

async function watchUser(auth) {
    const gmail = google.gmail({version: 'v1', auth});
    const res = await gmail.users.watch ({
        userId: 'foo@bar.com',
        topicName: 'projects/yourproject/topics/your-gmail-topic',
        labelIds: ['Label_99999'],
        labelFilterBehavior: 'include'
    });
    console.log(res);
}
smoore4
  • 4,520
  • 3
  • 36
  • 55