Skip to content

Instantly share code, notes, and snippets.

@moayadhani
Last active March 7, 2024 21:05
Show Gist options
  • Star 38 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save moayadhani/fcb75d0bf5be50b83e36e05746e2722d to your computer and use it in GitHub Desktop.
Save moayadhani/fcb75d0bf5be50b83e36e05746e2722d to your computer and use it in GitHub Desktop.
Get Gmail Emails By Assigned Label
var ui = SpreadsheetApp.getUi();
function onOpen(e){
ui.createMenu("Gmail Manager").addItem("Get Emails by Label", "getGmailEmails").addToUi();
}
function getGmailEmails(){
var input = ui.prompt('Label Name', 'Enter the label name that is assigned to your emails:', Browser.Buttons.OK_CANCEL);
if (input.getSelectedButton() == ui.Button.CANCEL){
return;
}
var label = GmailApp.getUserLabelByName(input.getResponseText());
var threads = label.getThreads();
for(var i = threads.length - 1; i >=0; i--){
var messages = threads[i].getMessages();
for (var j = 0; j <messages.length; j++){
var message = messages[j];
if (message.isUnread()){
extractDetails(message);
GmailApp.markMessageRead(message);
}
}
threads[i].removeLabel(label);
}
}
function extractDetails(message){
var dateTime = message.getDate();
var subjectText = message.getSubject();
var senderDetails = message.getFrom();
var bodyContents = message.getPlainBody();
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
activeSheet.appendRow([dateTime, senderDetails, subjectText, bodyContents]);
}
@kousiknaga
Copy link

kousiknaga commented Oct 15, 2022

@moayadhani Please assist with your script, how labeled emails will come in spreadsheet automatically instead of manually clicking on Gmail Manager then Get Emails.2ndly can I receive unique emails with unique subject line which arrived first time in this lebeled.

Thanks in advance.

@moayadhani
Copy link
Author

@kousiknaga

Hi,
Regarding the automatic extraction of Gmail emails, I have published a blog with simple steps that show how to do that. Here is the link:
https://codewondo.com/create_apps_script_triggers/

To extract the first email that arrives in the thread, you can replace line 21 to 27 with the following code:

var message = messages[0];
if (message.isUnread()){
  extractDetails(message);
  GmailApp.markMessageRead(message);
}

If you face a problem, please send me an email. My email is moa29000@gmail.com

@KietLeo67
Copy link

hi @moayadhani.
i want to get email header in a label. I used the above code but don't know how to replace the code to get the subject in the label. Can you help me. Thank you
function getGmailEmails() {
var strtIdx = 0;
var threadsToRead = 5;
let threads;
do {
threads = GmailApp.getInboxThreads(strtIdx, threadsToRead);
for (var i = 0; i < threads.length; i++) {
let messages = threads[i].getMessages();
for (let j = 0; j < messages.length; j++) {
var message = messages[j];
extractDetails(message);
}
}
strtIdx += threadsToRead;
} while (threads.length == threadsToRead);
}

function extractDetails(message) {
var dateTime = message.getDate();
var subjectText = message.getSubject();
var senderDetails = message.getFrom();
var identificativo = message.getId();

var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
activeSheet.appendRow([dateTime, senderDetails, subjectText, identificativo]);
}

@bkeneu
Copy link

bkeneu commented Oct 27, 2022

Hi, I have a strange issue, the script runs once and imports the mails to Google sheets but if I delete the data in the sheet and run the script again it does not import any emails. I have tried to generate new emails and run it again but still no luck.

Any ideas I could do to fix this?

@moayadhani
Copy link
Author

Hi @bkeneu,
Well, this seems to be an issue related to your maximum usage of Gmail emails read/write operations. Google has set daily quotas per users. You can check this from the link below:
https://developers.google.com/apps-script/guides/services/quotas

If you think this is not the problem, please send me an email over moa29000@gmail.com OR moayad@codewondo.com and I will help you out.

Best regards

@bkeneu
Copy link

bkeneu commented Oct 27, 2022

I found it , there is a if statement to only extract messages if they are unread - sorry

@moayadhani
Copy link
Author

Yes, I thought that by "generate new emails", you meant new encoming emails that are unread yet.
Anyways, I'm glad that you found a fix

@mtram8
Copy link

mtram8 commented Dec 10, 2023

Hi @moayadhani! Love your tutorial and appreciate your help in advance!

When I tried running the above (pasted below too) source code, I saw a box appear in the UI requesting for Label Name. When I provided the Label Name again, I see error messages that say Error resuming script execution and Script getGmailEmails experienced an error.

Can you please lmk what the source code should be so I can retrieve only email messages labeled General User Support?

Source Code

var ui = SpreadsheetApp.getUi();
function onOpen(e){

ui.createMenu("Gmail Manager").addItem("Get Emails by Label", "getGmailEmails").addToUi();

}

function getGmailEmails(){
var input = ui.prompt('Label Name', 'General User Support', Browser.Buttons.OK_CANCEL);

if (input.getSelectedButton() == ui.Button.CANCEL){
return;
}

var label = GmailApp.getUserLabelByName(input.getResponseText());
var threads = label.getThreads();

for(var i = threads.length - 1; i >=0; i--){
var messages = threads[i].getMessages();

for (var j = 0; j <messages.length; j++){
  var message = messages[j];
  if (message.isUnread()){
    extractDetails(message);
    GmailApp.markMessageRead(message);
  }
}
threads[i].removeLabel(label);

}

}

function extractDetails(message){
var dateTime = message.getDate();
var subjectText = message.getSubject();
var senderDetails = message.getFrom();
var bodyContents = message.getPlainBody();

var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
activeSheet.appendRow([dateTime, senderDetails, subjectText, bodyContents]);
}

@moayadhani
Copy link
Author

@mtram8
Hi! I am pleased you found this code helpful to you.

Regarding the issue you are facing, I guess the previous execution was not successful, and you ran the secod label extraction before the previous is done. That being said, it could be caused by other factors. Can you share with me a short screen recording of the problem and send over email at moa29000@gmail.com and cc moayad@codewondo.com

I will help you out with your issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment