Sending out emails as a part of a Google Workspace automated workflow is a very common task. In Google Apps Script we can send emails to users using the MailApp.sendEmail(), the GmailApp.sendEmail() method or even as a JSON payload with the Gmail Advanced API service.
While one might expect that the sender’s signature block would also be transmitted with the automated email, we find that this is not in fact the case.
So what do we do?
The video:
Extract the Primary Signature Block with Apps Script
Let’s say we want to add the following signature block to an automated email.
To do this, we will need to use the Gmail API advanced service.
- In your Apps Script project, select the Add a service plus button
- A dialogue box will appear. Scroll down until you find Gmail.
- Keep the identifier as it is and then select Add.
- The service should be added to the sidebar.
From here we can create a one-liner to extract the primary signature block HTML from the sender’s Gmail account.
1 |
const signature = Gmail.Users.Settings.SendAs.list("me").sendAs.find(account => account.isDefault).signature; |
The logged results for our example are a HTML string that looks like this:
1 |
<div dir="ltr"><img data-aii="CiExdkREN0F0bUpBV1JLT3FjQUdmZGJ1Szh6V01yeXhQcUs" width="94" height="96" src="https://ci3.googleusercontent.com/mail-sig/AIorK4xE20plcFRGsot4HlDQu9L0X_Yuf3-frQWSVFVIOP10cuFj5fro0pJ4wJw26N5S2C6IWBMTBhI" data-os="https://lh3.googleusercontent.com/d/1vDD7AtmJAWRKOqcAGfdbuK8zWMryxPqK"> <font size="6">Yagi</font><div><font size="4">Coding enthusiastically!</font><br><div><br></div></div></div> |
I don’t see my signature HTML
If, after logging your signature and you don’t see anything, check your email configuration in Gmail under Settings > General > Signature. Ensure that you have selected a signature as default, ‘For new email use’.
Understanding the One-Liner
Gmail.Users.Settings.SendAs ...
This first section of the code identifies the API path. Here we are looking at the sender’s (user’s) settings for any of the user’s aliases.
... .list("me") ...
To extract the details of the settings for the active user, the person running the script, we can use the shorthand, “me”, rather than identifying a specific email.
From this point, we would get an array of objects, one for each of the user’s aliases.
For our example user, the object would look like this:
1 2 3 4 5 6 7 |
{ sendAs: [ { replyToAddress: '', isPrimary: true, isDefault: true, displayName: '', signature: '<div dir="ltr"><img data-aii="CiExdkREN0F0bUpBV1JLT3FjQUdmZGJ1Szh6V01yeXhQcUs" width="94" height="96" src="https://ci3.googleusercontent.com/mail-sig/AIorK4xE20plcFRGsot4HlDQu9L0X_Yuf3-frQWSVFVIOP10cuFj5fro0pJ4wJw26N5S2C6IWBMTBhI" data-os="https://lh3.googleusercontent.com/d/1vDD7AtmJAWRKOqcAGfdbuK8zWMryxPqK"> <font size="6">Yagi</font><div><font size="4">Coding enthusiastically!</font><br><div><br></div></div></div>', sendAsEmail: 'tester@yagisanatode.com' } ] } |
... .sendAs. ...
First, to get into the array we need to call the sendAs
property.
We wouldn’t want to extract a signature block another alias so we will ensure that we are using our default email.
... .find(account => account.isDefault) ...
To do this we can use the JavaScript ‘find’ method. This takes a function as an argument. Here we have used a simple arrow function where ‘account’ is our iterator for each array. If the default for the currently iterated account is true then we want to extract the signature string.
... .signature
Finally, we extract the signature as a HTML string.
Adding it to your code
Here is a simple example of how you can append the signature to an email.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function sendEmail() { const signature = Gmail.Users.Settings.SendAs.list("me").sendAs.find(account => account.isDefault).signature; const message = `Hi! I just wanted to reach out and say. You, yes you are awesome! Cheers,` const body = message + "<br><br>" + signature; GmailApp.sendEmail("person@example.com","Daily reminder!",null,{ htmlBody: body }) }; |
It is important to note here that instead of adding a plain text body to the sendEmail
method of GmailApp (Line 13) we have instead used the optional object insertion and added the htmlBody
property.
Then, above on line 10, we combine the message with the signature ensuring we have a couple of line breaks between the two to provide good separation.
Note that you may even need to add further HTML formatting to the original message to ensure line spacing is maintained.
Accessing your other Gmail Signatures with Apps Script
So, you might be thinking,
‘I like to send different signature blocks for different circumstances. How do I do that?’
Whelp, my dear friends, as of writing this, you can’t access them at all using Gmail Advanced services. Indeed many developers are more than a little miffed at this and have been so for a number of years.
‘Well now! I’m a bit cranky about this too, if only there were a place to proactively express my displeasure at those who may be able resolve this problem.’
Support the current feature request
Head over to Google’s issue tracker now and add your vote and perhaps, a comment to request this feature:
Plan B: Using Drafts
In the meantime, we can store our alternate signature in a draft email with a unique subject line.
Here is our example of the secondary signature as a draft email:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/** * Retrieves a draft containing the desired signature block. * @param {String} draftSubject - Unique subject line for the sign block stored in the email draft. * @returns {String} HTML formatted string of the selected signature block. */ function draftTextSignature(draftSubject){ const signatureDraft = GmailApp.getDrafts().find( signature =>{ const subject = signature.getMessage().getSubject(); return subject === draftSubject }); return signatureDraft.getMessage().getBody(); }; |
We can call this function from wherever we are sending our email. The draftTextSignature
function takes the subject line of our draft email containing our desired signature block. So for our example, it would be this:
const signature = draftTextSignature("Gmail Signature Block 2");
Line 8: Retrieves all the user’s draft emails with the getDrafts()
method of the GmailApp class.
Then we again use the JavaScript ‘find’ method to search for the draft containing our desired subject line. Keep in mind that ‘find’ takes a function with an iterating parameter we set to ‘signature’.
Line 10: As the code looks through each draft we extract the subject line from the draft message.
Line 12: We then compare the current subject with our target subject line and if there is a match, ‘find’ stops and returns the current draft.
Line 16: Finally, we retrieve the body from the found message.
All-in-one Retrieve Selected Gmail Signature Function for Apps Script
If you want to have the flexibility to either extract the primary signature or retrieve one from a predefined Gmail draft then you could use this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
/** * Retrieves either the user's primary signature block or one stored in a draft. * @param {String} [draftSubject] - Optional unique subject line for the sign block stored in the email draft. * @returns {String} HTML formatted string of the selected signature block. */ function getSignatureBlock(draftSubject = null){ if(!draftSubject){ return Gmail.Users.Settings.SendAs.list("me").sendAs.find(account => account.isDefault).signature; }else{ const signatureDraft = GmailApp.getDrafts().find( signature =>{ const subject = signature.getMessage().getSubject(); return subject === draftSubject }); return signatureDraft.getMessage().getBody(); }; }; |
Try this runsies()
function out to test the code:
1 2 3 4 5 6 7 8 9 |
function runsies(){ const signature = getSignatureBlock(); console.log(signature) const signature2 = getSignatureBlock("Signature w phone") console.log(signature2) } |
Just make sure you change the getSignatureBlock
argument to the subject line for the draft email containing your signature.
~Yagi