2021-07-31

Using script to search Gmail subject line for a cells value, then forward email

What I am attempting to do is to use some script to automate locating then forward to a specific email without having to switch over to Gmail to manually forward this on, However I cannot use the auto forward built into Gmail due to only certain emails needing to be sent, There are also multiple emails with the same reference number in the subject field unless I add in the constant then there is only one,

The emails subject get sent to me in the following format a unique reference number followed by hyphen then the constant (123456 - Constant),

Currently I am attempting to use the built in Gmail search via reference number + Constant, The reference number is stored in a google sheets cell, I have then been tagging on the "constant" within the script.

However despite using "" which to my understanding is for an exact match, this is forwarding multiple entries with different reference numbers,

Currently the code I am attempting to use is

function Search2() {

  var sheet   = SpreadsheetApp.getActiveSheet(); //gets sheet
  var row     = 1;
  var col     = 8;
  var REF = sheet.getRange(row, col).getValue(); //gets value of the unique reference number

  var threads = GmailApp.search('subject:"REF"+"CONSTANT"') //adds in the constant for the search
  for (var h = 0; h < threads.length; h++) {
    var messages = threads[h].getMessages();
    for (var i = 0; i < messages.length; i++) {
              Logger.log(messages[i].getSubject());
                messages[i].forward("EMAIL ADDRESS", {
          cc: "",
          bcc: ""
          });     
      
  }
}
}

My current line of thought is that there must be something not working correctly when I combine the reference and the constant causing it to not look for an exact match and returning closest matches.

Any assistance would be appreciated,

Update 30/07/2021 @ 18:46 - I did a bit of testing replacing the "REF" directly with the reference number works and returns 1 result forwarded, This leads my thought process to there is an issue with the REF variable pulling through the correct value.



from Recent Questions - Stack Overflow https://ift.tt/3lm5Eh4
https://ift.tt/eA8V8J

No comments:

Post a Comment