Search code examples
google-apps-scriptgmailgmail-api

Get Email Sender's Display Name


I'm trying to get the email sender's display name, not their email address (I want to get "John Doe", not "[email protected]"). From what I understand, the display name value is optional so not all emails will have this.

Is there a way to get the email sender's display name? Below is the test code that I have been working on.

function myTestFunction() {

var threads = GmailApp.search("in:spam");

  for (var i = 0; i < threads.length; i++) {
  var msg = threads[i].getMessages()[0];

    console.log(i);

    if (msg.getHeader("Display-Name").match(/(John Doe)|(Jane Doe)/gi) !== null) {
      console.log('Found it!')
      continue;
    } 
  }   
}

Solution

  • The problem with the code is the header being looked at, the best place to find the name is under the "From" header, there you will see both the email and display name of the account sending the email, I believe this code should work

    function myTestFunction() {
    
    var threads = GmailApp.search("in:spam");
    
      for (var i = 0; i < threads.length; i++) {
      var msg = threads[i].getMessages()[0];
        if ((((msg.getHeader("From")).split("<"))[0]).match(/(John Doe)|(Jane Doe)/gi) !== null) {
          console.log('Found it!')
          continue;
        } 
      }   
    }
    

    The split part that shows after the message header is because the email address is always in between <> so the split is meant to only take the part of the name, this also accounts for emails where the displayname is not present as the split will return the full email address in those scenarios and as such will fail the match.

    Hope this helps!