Issue with GetUserLabelByName Google App Script - google-apps-script

I'm trying to use "getUserLabelByName" to only retrieve email threads labeled with "MyLabel", but the script is also pulling emails from the "Sales", "Marketing" labels. These emails do not have the "MyLabel" label and I can't figure out why they would be included in the array when I've specifically told App Script to only pull emails with the label "MyLabel".
I added the Logger.log(To); so that I could see which email addresses were being logged. For background, all emails coming to a certain address, for instance info#company.com should be marked with the label "MyLabel", while other emails sent to other email addresses are assigned different labels. So if were are only collecting emails from "MyLabel", there should be no reason to see any other email addresses in the log other than "info#company.com", but there are other email addresses being captured and I can't figure out how to fix the issue.
function getEmail() {
var label = GmailApp.getUserLabelByName("MyLabel");
var threads = label.getThreads();
Logger.log(label);
//get first message in first thread
for (var i = 0; i < threads.length; i++) {
var messages=threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var message=messages[j];
var To=message.getTo();
Logger.log(To);
Logger.log(message.getFrom());
Yes, there is more to this script but this section is the part with the issue.

Related

Most efficient way to traverse Gmail attachments and download to Google Drive?

Using Google Apps Script, is there a more efficient way to traverse my Gmail - picking out 'non-starred' emails that have a particular label assigned to them and then download the attachments to Google Drive?
My code works, but typically 'times out' after processing about 25 image attachments (using non-paid Gmail account)
The piece of code that does the work is as follows:
// Loop through the messages for each thread
for (var i = 0 ; i < messages.length; i++) {
for (var j = 0; j < messages[i].length; j++) {
var CurrentMsg = messages[i][j];
if (!CurrentMsg.isStarred()){
var att = CurrentMsg.getAttachments();
// If there were no attachments, create a 'dummy text file' to notify the user that there were no attachments for that email.
var MsgSubject = CurrentMsg.getSubject();
if (att.length == 0){
var file = folder.createFile(MsgSubject,'There were no attachments',MimeType.PLAIN_TEXT);
}
else{
for (var k = 0; k < att.length; k++){
var file = folder.createFile(att[k].copyBlob().getAs('image/jpeg').setName(MsgSubject));
}
}
CurrentMsg.star();
}
}
}
Any tips gratefully received!
If you want to look through certain emails only, like those that are not starred in your case, consider using the search() method. This will help you avoid looping over threads and messages you don't need.
If you need to bypass your maximum execution time, check out this answer and this article (also linked in the answer).
I would recommend limiting results via a query then using the foreach function to go through messages:
// limit the list of messages to iterate through
var query = 'has:attachment label:particular';
var results = Gmail.Users.Messages.list(userId, {q: query});
results.messages.forEach(function (m) {
var msg = GmailApp.getMessageById(m.id);
msg.getAttachments().forEach(function (a) {
var fileName = a.getName();
fileName = saveAttachmentToFolder(folder, a, fileName, msg.getDate(), input.tz);
});
});
The code snippet above is based on a Gmail add-on that I created, specifically for saving attachments to labeled folders in Drive: https://github.com/ellaqezi/archiveByLabel/blob/main/Code.gs#L24
In the label field, you can define nested directories to create in Drive e.g. foo/bar.
In the query field, you can copy the parameters as you would use them in Gmail's search bar.

Getting the body of individual emails from gmail to google sheets

I'm really new at using Google Apps Script, so if what I'm trying doesn't make sense, or just isn't possible please let me know.
Everyday I get several emails that look like the following:
Your Name: FirstName LastName
Phone Number: 555 867 5309
Email Address: FakeEmail#email.com
What do you need help with? Request someone makes.
I'm attempting to automatically send the body of these emails to a new line in a Google Sheet when they come in.
As of right now I have every email get the label "myLabel" when it comes in. I then run the following script, which is a slightly modified version of something I found here:
function myFunction() {
var ss = SpreadsheetApp.getActiveSheet();
var label = GmailApp.getUserLabelByName("MyLabel");
var threads = label.getThreads();
for (var i=0; i<threads.length; i++)
{
var messages = threads[i].getMessages();
for (var j=0; j<messages.length; j++)
{
var msg = messages[j].getBody();
ss.appendRow([msg])
}
threads[i].removeLabel(label);
}
}
I'm attempting to run this code with a timer trigger every 15 minutes. The issue I've run into is that every time the code runs it pulls from every email in the thread. I would like it to just pull from the emails that are new since the last time it ran. Any advice would be greatly appreciated.
Why not mark the messages as read when you finish processing them? Here is a sample from one of my scripts.
var pendingEmailLabel = "MyLabel";
var threads = GmailApp.getUserLabelByName(pendingEmailLabel).getThreads();
for (var t = 0; t < threads.length; ++t) {
var thread = threads[t];
var messages = thread.getMessages();
for (var m = 0; m < messages.length; ++m) {
var message = messages[m];
if (message.isUnread()) {
// INSERT YOUR CODE HERE THAT TAKES ACTION ON THE MESSAGE
message.markRead();
}
}
}
}

Forward email message with MailApp instead of GmailApp

Forward emails with MailApp instead of GmailApp to preserve emojis.
We have a filter to tag emails we want to forward.
And then a google-apps-script to parse those emails and forward them.
Encountered a problem where using GmailApp.forward having a problem with some emojis. (ref. my previous question)
The solution was to send the email with MailApp instead of GmailApp.
But MailApp does not have a forward function like GmailApp's GmailMessage :(
So how do I fix this code?
var label = 'WisWebRelay';
var threads = GmailApp.getUserLabelByName(label).getThreads();
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var email = messages[j];
email.forward('my#email.com');
}
}
Will I have to get html-message, all inline images and attachment from my mail object, and build a message and send with MailApp.sendEmail?

-label:pinned works in Gmail but not in the Google Apps Script GmailApp.search() function?

The following Gmail / Inbox By Gmail search returns everything in my inbox that is pinned.
in:inbox label:pinned
And this returns all unpinned inbox messages.
in:inbox -label:pinned
side note: Even though messages are "pinned" in Inbox By Gmail, and not Gmail, the search still works as expected in both web apps.
The following Google Apps Script logs only pinned emails.
function GetUnpinnedEmails() {
var threads = GmailApp.search('in:inbox label:pinned');
for (var i = 0; i < threads.length; i++) {
message = threads[i].getMessages()[0];
subject = message.getSubject();
Logger.log(subject)
}
}
However, the following Google Apps Script logs all inbox emails including pinned messages.
function GetUnpinnedEmails() {
var threads = GmailApp.search('in:inbox -label:pinned');
for (var i = 0; i < threads.length; i++) {
message = threads[i].getMessages()[0];
subject = message.getSubject();
Logger.log(subject)
}
}
GmailApp.search('in:inbox NOT label:pinned') also returns all inbox messages.
I think this is a bug but I thought I'd see if I'm missing something. Thanks.

reply time between threads [google apps script]

I want to develop a script in GAS to get the reply time of all of my threads in Gmail in a specific period. The example script below seems to be a way, but im not sure on how to proceed.
function processInbox() {
// get all threads in inbox
var threads = GmailApp.getInboxThreads();
for (var i = 0; i < threads.length; i++) {
// get all messages in a given thread
var messages = threads[i].getMessages();
// iterate over each message
for (var j = 0; j < messages.length; j++) {
// log message subject
Logger.log(messages[j].getSubject());
}
}
};
Maybe use:
Google Documentation - getDate() GmailMessage Class
When you say you want to "get" the information, how do you want to get it? Be sent an email? Store it in a spreadsheet? Record it in a .csv file?