Created
July 13, 2022 16:01
-
-
Save your-diary/0956a731de3b035a67644fa78ec0bb60 to your computer and use it in GitHub Desktop.
gas to check new gmails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function f() { | |
const newMails = checkNewMail(); | |
//arbitrary operation | |
newMails.forEach(console.log); | |
} | |
function checkNewMail(): GoogleAppsScript.Gmail.GmailMessage[] { | |
const sheetName = 'id'; | |
const searchString = 'from:[email protected]'; | |
const numThread = 10; | |
const idSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName); | |
if (idSheet === null) { | |
throw new Error(`Sheet [ ${sheetName} ] not found.`); | |
} | |
let lastRow = idSheet.getLastRow(); | |
if (lastRow === 0) { | |
idSheet.getRange('A1:H1').setValues([['id', 'timestamp', 'subject', 'from', 'to', 'cc', 'bcc', 'body']]); | |
idSheet.getRange('A1:1').setBackground('#cccccc'); | |
idSheet.setFrozenRows(1); | |
++lastRow; | |
} | |
const existingIds = idSheet.getRange(`A1:A${lastRow}`).getValues().slice(1).map(l => l[0].toString()); | |
const newMails = GmailApp.search(searchString, 0, numThread) | |
.reduce( | |
(l: GoogleAppsScript.Gmail.GmailMessage[], thread) => { | |
l.push(...thread.getMessages()); | |
return l; | |
}, | |
[] | |
) | |
.filter(mail => !existingIds.includes(mail.getId())); | |
if (newMails.length != 0) { | |
idSheet.getRange(`A${lastRow + 1}:H${lastRow + newMails.length}`).setValues( | |
newMails.map(mail => [ | |
mail.getId(), | |
mail.getDate(), | |
mail.getSubject(), | |
mail.getFrom(), | |
mail.getTo(), | |
mail.getCc(), | |
mail.getBcc(), | |
mail.getPlainBody(), | |
]) | |
); | |
} | |
return newMails; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment