Search code examples
google-apps-scriptgmail

Is there a way to get the specific email address from a Gmail message object in Google app scripts?


In Google App Scripts to process a list of email messages in my inbox. From the messages I need to get the from and to addresses of each message. When I use the message.getFrom() method to get the from address it returns something like this: "FirstName LastName ". But, what I want is the plain email address: "[email protected]" I can't find a method on the GmailApp object, or the Message object, that would return just this information.

getFrom() returns a simple string, not an address object that can be dissected further. Am I missing something?


Solution

  • getFrom() method should return the sender of the message in the format Some Person <[email protected]>. If you need just the email address portion of the string, you can extract it using regular expression like this (adapted example from getFrom() method description):

    var thread = GmailApp.getInboxThreads(0,1)[0]; // get first thread in inbox
    var message = thread.getMessages()[0]; // get first message
    Logger.log(message.getFrom().replace(/^.+<([^>]+)>$/, "$1"));
    

    That regex replace the string returned by getFrom() method with the part of the string in angle brackets (the sender's email address).