Search code examples
google-apps-scriptgmail-api

How do I get to show my name as sender in the emails send from app script?


My code now looks like this:

GmailApp.sendEmail(address, subject, body, {htmlBody : body});

My Reference Question: Syntax Error for adding signature to email created from sheets using apps script for

My Issue: It shows sender as alex.ken@....

What I want: I want Scripts to take the name of the users. All users have set different names for their email address in Google Settings.

PS - Please note I have multiple users using the sheet/macro so I can't have fix value in the name parameter.

Please please help.

Edit 1=Solution:

var user = Session.getActiveUser().getUsername(); //gives username
var firstpart = user.split('.')[0]; //gives first part of username
var uppercase = firstpart.charAt(0).toUpperCase() + firstpart.substring(1); //makes first letter upper case
var display = uppercase + " with Ban Company";
.
.
.
.
GmailApp.sendEmail(address, subject, body, {htmlBody : body + signature,cc: "[email protected]",name:display});


Solution

  • Your solution will work for emails in the format name.surname@..., but if the user has something else like itadmin@..., a nickname, or any other email variant you may run into issues.

    An alternative solution would be to use the People API Advanced Services to retrieve the current user's Profile name, since Apps Script's Session.getActiveUser() only includes the user's email and there are some scenarios where it won't work.

    This includes more steps and they'll have to authorize the People API but you can get any user's profile name.

    1. Enable the Advanced Service in the Apps Script editor by clicking the + next to Services. You can then add the People service.

    Adding a service

    1. Add the profile scope to your project by editing the appscript.json manifest file.
      {
        ...
        "oauthScopes": [
          "https://www.googleapis.com/auth/userinfo.profile"
        ],
       ...
      }
    
    1. Add a function that will retrieve the current user's profile name information from the People API.
    //This will contain a user's names
    function getCurrentUser(){
      var currentuser = People.People.get("people/me", {"personFields":"names"})
      return currentuser.names[0]
    }
    
    var firstname = getCurrentUser().givenName //gets the user's first name
    var fullname = getCurrentUser().displayName // gets the user's full profile name
    
    //You can then add either variable as the name 
    
    GmailApp.sendEmail(address, subject, body, {htmlBody : body + signature,cc: "[email protected]",name:firstname});
    
    
    

    In case you need it you can also retrieve much more than just the names, but also other user profile info. Check out the documentation here.