Skip to content

Instantly share code, notes, and snippets.

@ChaiyachetU
Created September 9, 2021 11:21
Show Gist options
  • Save ChaiyachetU/2f07c0b3beb873f80b84abc1fe1b1457 to your computer and use it in GitHub Desktop.
Save ChaiyachetU/2f07c0b3beb873f80b84abc1fe1b1457 to your computer and use it in GitHub Desktop.
// get priority unread emails
function getPriorityUnreadEmails() {
let priorityUnreadEmails = [];
// priority inbox unread emails
const priorityInboxUnread = GmailApp.getPriorityInboxUnreadCount();
Logger.log("Priority inbox unread : " + priorityInboxUnread);
// new priority inbox emails
if (priorityInboxUnread) {
// retrieves all priority inbox unread threads
const allPriorityInboxUnreadThreads = GmailApp.getPriorityInboxThreads(0, priorityInboxUnread);
allPriorityInboxUnreadThreads.forEach((priorityInboxUnreadThread) => {
let unreadEmailMessage = "";
// gets the messages in priotiry inbox unread thread
const messages = priorityInboxUnreadThread.getMessages();
messages.forEach((message) => {
// gets the sender of this message
const sender = extractEmails(message.getFrom());
// check sender is priority contact list
const isPriorityContact = priorityContactListEmails.includes(sender);
// new inbox is my contact list emails
if (isPriorityContact) {
// sender
Logger.log("New Inbox Email From My Contact List : " + sender);
unreadEmailMessage += "\n\n📥New email from : " + sender;
// email subject
const emailSubject = message.getSubject();
Logger.log("Email Subject :" + emailSubject);
unreadEmailMessage += "\n\n🏷️Subject : " + emailSubject;
// email contents with replaces all 3 types of line breaks with single line break (\n) and more white space with single white space
const emailContents = message.getPlainBody().replace(/(\r\n|\n|\r)+/g, "\n").replace(/( )+/g," ");
Logger.log("Email Content :" + emailContents);
if (emailContents.length < 300) {
unreadEmailMessage += "\n\n📋Contents : " + emailContents;
} else {
unreadEmailMessage += "\n\n📋Contents : " + emailContents.slice(0, 300) + "...";
}
// email attatchments
const attatchments = message.getAttachments();
if (attatchments.length !== 0) {
// get attachment file url for download
const attachmentFileUrls = saveAttachmentFiles(attatchments, attachmentFolderId);
attachmentFileUrls.forEach(fileUrl => unreadEmailMessage += "\n\n🔗Attachment File : " + fileUrl);
}
// marks the message as read
message.markRead();
// stars the message
message.star();
// reloads this message and associated state from Gmail
message.refresh();
// reply to sender
message.reply("Got your message, Thank you.✌️\n\n" + "Chaiyachet ✌️\n\n" + "This email is auto-generated. Please do not reply.");
}
// add messages for send to line notify
if (unreadEmailMessage !== "") {
priorityUnreadEmails.push(unreadEmailMessage);
}
})
})
} else {
Logger.log("📥 No new priority inbox unread ✌️");
}
return priorityUnreadEmails;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment