google-apps-scriptgmailx-forwarded-for

How to filter Gmail headers and stop "via" into labels


I have tried several ways to filter a type of email into a label but the filter doesn't work.

I used Google to find a script to move these kind of emails into SPAM, but these emails are not SPAM for me. Instead, I just want to modify the script to move these emails to a certain label.

This is the script that I found:

var threads = GmailApp.getInboxThreads(0, 5);

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 body=message.getRawContent();

        if(body.indexOf("X-Forwarded-For: email@example1.com email@example2.com")>-1)
        {
            GmailApp.moveThreadToSpam(threads[i]);
        }

        Utilities.sleep(1000);
        }
    }
}

X-Forwarded-For: email@example1.com email@example2.com is the email address that I find in the "Show Original" option from the drop down menu.

Can you please help me modify the script to move these specific types of emails into labels and not spam?


Solution

  • Edit:

    The script is moving messages to the spam folder because of this line: GmailApp.moveThreadToSpam(threads[i]);

    If you want to apply a label to the messages instead of marking them as spam, you can use threads[i].addLabel(label). And to archive the messages so they move out of the inbox, you can use threads[i].moveToArchive().

    Here's an updated example for you:

    var threads = GmailApp.getInboxThreads(0, 5);
    
    var label = GmailApp.getUserLabelByName("LABEL NAME GOES HERE");
    
    if (label == null) 
    {
        var label = GmailApp.createLabel(label);
    }
    
    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 body=message.getRawContent();
    
            if(body.indexOf("X-Forwarded-For: email@example1.com email@example2.com")>-1)
            {
                threads[i].moveToArchive();                
                threads[i].addLabel(label);
            }
    
            Utilities.sleep(1000);
            }
        }
    }
    

    That modified version allows you to specify the name of the label at the top. If the label doesn't already exist, it will create it. And then rather than moving the message to spam, it will archive it and apply your selected label to it instead.