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

后端 未结 2 1854
天命终不由人
天命终不由人 2020-12-11 09:44

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.getF

相关标签:
2条回答
  • 2020-12-11 10:30

    After you get the GmailMessage object, you can get the email address by first getting the RFC Header named "From" using GmailMessage.getHeader("From"), and then apply a certain Regular Expression to it.

    Like this:

     // Get email from RFC Header "From"
     var rfcHeaderFrom = message.getHeader("From");
     var rfcHeaderFromMailRegex = /[^< ]+(?=>)/g;
    
     var mailSender = rfcHeaderFrom.match(rfcHeaderFromMailRegex)[0];
    

    That will return an email address like: "user@example.com"

    0 讨论(0)
  • 2020-12-11 10:31

    getFrom() method should return the sender of the message in the format Some Person <someone@somewhere.com>. 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).

    0 讨论(0)
提交回复
热议问题