Search code examples
google-apps-scriptgoogle-sheetsgmail

Extracting Emails from Gmail Label to Google Sheet


Im trying to extract emails from a specific Gmail Label to Google sheet, using Google App Script, the data in Google sheet to have timestamp, from email, to email, subject, and email body.

enter image description here

I have tried using this App Script from the link below but i am getting error message when i run it.

// Original: https://github.com/TiagoGouvea/gmail-to-google-sheets-script/

Doc link


Solution

  • Extracting Emails

    function ExtractingEmails(query="Label:Test") {
      let o = [["TimeStamp", "From", "To", "Subject", "Body"]];
      const ts = GmailApp.search(query);
      ts.forEach(t => {
        let ms = t.getMessages();
        ms.forEach(m => {
          o.push([m.getDate(), m.getFrom(), m.getTo(), m.getSubject(), m.getPlainBody()])
        })
      })
      const ss = SpreadsheetApp.getActive();
      const sh = ss.getSheetByName("Sheet0");
      if (o && o.length > 1) {
        sh.clearContents();
        sh.getRange(1, 1, o.length, o[0].length).setValues(o);
        ss.toast(`${o.length - 1} messages found for Query: ${query}`)
      } else {
        ss.toast(`No messages found for Query: ${query}`)
      }
    }