##sendAndLabel(recipient, subject, body, options, label)##
An alternative to GmailApp.sendEmail(), which applies a label to the message thread in the sender's account.
Sends an email message with optional arguments. The email can contain plain text or an HTML body. The size of the email (including headers, but excluding attachments) may not exceed 20KB.
Original StackOverflow question: How to create a Gmail message with a specific label?
###Parameters###
Name | Type | Description |
---|---|---|
recipient |
String | the addresses of the recipients |
subject |
String | the subject line |
body |
String | the body of the email |
options |
Object | a JavaScript object that specifies advanced parameters, as documented for GmailApp.sendEmail() |
label |
String | the label to be applied |
The Google Apps Script GmailApp API does not give a way to add a label to a message as you send it, something you can do from the UI. This appears as Issue 1859 in the issue tracker, visit and star it for updates.
A work-around would be to take advantage of the thread apis. If the message is blind-copied (bcc'd) to the sender, it will also appear as a new message in their inbox, where we can use getInboxThreads()
to find it. Add the label to this thread, and optionally mark it read then archive it.
##inline(htmlWstyle)##
Convert html containing <style>
tags to instead have inline css.
This example uses an online service from MailChimp Labs, but the same principle could be used to leverage several other online providers.
Strictly speaking, this isn't not a gmail utility, but since it's so useful for producing cross-client compatible emails, here it is!
Original StackOverflow question: How do I use Google Apps Script to change a CSS page to one with inline styles?
###Parameters###
Name | Type | Description |
---|---|---|
htmlWstyle |
String | A block of HTML text including <style>..</style> tags. |
There are numerous online tools that do this conversion, so you could leverage one of them from Google Apps Script. (If you only need to do this once in a while, why not just use one of those services?)
This utility builds on the getElementByVal()
function from this answer.
There may appear to be some black magic in there. A previous answer described how to use the old Xml Service to examine the structure of a web page to find the bits you wanted. It's still good reading, but that service is now gone, and the new XmlService doesn't have equivalent exploratory support.
To start, we found a web service that did the job we were interested in, and used the UrlFetch Service to simulate a person pasting code into the service. Ideally, we'd like one that returned just the result we wanted, in a format we could use without any further work. Alas, what we had was a complete web page, and that meant that we'd have to farm it for our result. Basic idea there: Use the XmlService to parse and explore the page, extracting just the bit we wanted.
In the Css Inline service that was selected, Chrome's ability to "Inspect Element" was used to determine the tag type (<textarea>
) and a way to uniquely identify it (name="text"
). Armed with that knowledge, we had everything we needed to use getElementByVal()
to dig through the HTML returned from a POST request. (Alternatively, you could use String methods to find and extract the text you want.)
But when that was all put together, XmlService kept complaining about the format of the HTML in the result page - so JavaScript String & RegExp methods were used to balance the malformed tags before passing the page on.
Here's a simple example illustrating use of the inline()
function. Note that style information is absorbed from both the external css link AND the tagged styling.
function test_inline() {
var myHtml =
'<html>'
+ '<head>'
+ '<title>Example</title>'
+ '<link rel="stylesheet" href="http://inlinestyler.torchboxapps.com/static/css/example.css" ></link>'
+ '</head>'
+ '<body>'
+ '<style type="text/css">'
+ 'h1{'
+ 'color:yellow'
+ '}'
+ '</style>'
+ '<h1>An example title</h1>'
+ '<p>Paragraph 1</p>'
+ '<p class="p2">Paragraph 2</p>'
+ '</body>'
+ '</html>';
var inlined = inline(myHtml);
debugger; // pause in debugger, have a look at "inlined"
}
<html>
<head>
<title>Example</title>
</head>
<body>
<h1 style="color: yellow;">An example title</h1>
<p style="margin: 0;padding: 0 0 10px 0;">Paragraph 1</p>
<p class="p2" style="margin: 0;padding: 0 0 10px 0;">Paragraph 2</p>
</body>
</html>
Simplified OAuth2 authorization for Google Apps Script use of the GMail API. Fair warning: while this is an illustration of how to do OAuth2 authentication, it's not really necessary since the addition of ScriptApp.getOAuthToken()
.
-
Requires OAuth2 for Apps Script, library ID MswhXl8fVhTFUH_Q3UOJbXvxhMjh3Sh48
-
See OAuth2 for Apps Script for details including installation of the library.
-
Set your project-specific values in an "authorization profile" object, e.g.
var gmailAuthProfile = { // Get the client ID and secret from the Google Developers Console. clientId : '--redacted--.apps.googleusercontent.com', clientSecret : '--redacted--', // Set the project key of the script using the service. projectKey : '--redacted--' }
-
Authorize. See comments on
doGet()
. -
Use
getGmailService().getAccessToken()
as authorization bearer for calls to gmail API.
Using the GMail service provided by Google Apps Script you can script many GMail capabilities. One thing you cannot do is directly send existing draft messages.
This script contains a few utilities (maybe the foundation of a library, someday) that deal with draft emails, including using the GMail API to retrieve and send draft messages.
No more need to resort to generating a whole new copy of a draft, send the copy, delete the draft... instead:
sendDraftMsg( msgId ); // Will find the draft with this msgId, and send it
This will preserve all the attributes of the draft email... To:, From:, CC: and BCC: lists, labels, inline images, attachments, and formatting.
###sendDayOldDrafts()
Written for StackOverflow question How to send a draft email using google apps script. Sends all draft emails labeled "send-tomorrow".
A simple example of how to use sendDraftMsg()
.
Sends a draft message that matches the given message ID.
Parameters
Name | Type | Description |
---|---|---|
messageId |
String | Immutable Gmail Message ID to send |
subject |
String | the subject line |
Returns
Type | Description |
---|---|
Object | Response object if successful, see https://developers.google.com/gmail/api/v1/reference/users/drafts/send#response |
Gets the current user's draft messages.
Returns
Type | Description |
---|---|
Object[] | If successful, returns an array of `Users.drafts` resources. (https://developers.google.com/gmail/api/v1/reference/users/drafts) |
Gets the draft message ID that corresponds to a given Gmail Message ID. Parameters
Name | Type | Description |
---|---|---|
messageId |
String | Immutable Gmail Message ID to search for |
Returns
Type | Description |
---|---|
String | Immutable Gmail Draft ID, or `null` if not found |
Gets the draft message content that corresponds to a given Gmail Message ID.
Parameters
Name | Type | Description |
---|---|---|
messageId |
String | Immutable Gmail Message ID to search for |
optFormat |
String | Optional format; `'object'` (default) or `'json'` |
Returns
Type | Description |
---|---|
Object or String | If successful, returns a `Users.drafts` resource. (https://developers.google.com/gmail/api/v1/reference/users/drafts) |
Using the GMail service provided by Google Apps Script you can script many GMail capabilities. One thing you cannot do is label messages, you can only label threads. These utilities provide the ability to modify the labels on a single message, by use of the GMail API.
See labelMessage.gs for code.
Example of use:
function test_modifyMessage() {
var firstThread = GmailApp.getInboxThreads(0,1)[0];
var message = firstThread.getMessages()[0];
var messageId = message.getId();
modifyMessage('me', messageId, ['stack','overflow']); // add two labels
modifyMessage('me', messageId, null, ['stack','overflow']); // remove two labels
}
###modifyMessage()
Written for StackOverflow question Add label to specific message, not the thread. Adds or removes Labels on an individual message.
Parameters
Name | Type | Description |
---|---|---|
userId |
String | User's email address. The special value 'me' can be used to indicate the authenticated user. |
messageId |
String | ID of Message to modify. It's the same as message.getId() in Google Apps Script's GmailMessage object. It's not a value of the 'Message-ID' header in message.getRawContent(). |
labelsToAdd |
String[] | Array of Label names to add |
labelsToRemove |
String[] | Array of Label names to remove |
Returns
Type | Description |
---|---|
Object | Users.messages resource, see https://developers.google.com/gmail/api/v1/reference/users/messages#resource |
Get the Label ID for the given labelName
. If Label isn't found, it will be created depending on the state of ok2Create
.
Parameters
Name | Type | Description |
---|---|---|
labelName |
String | Name of label to retrieve ID for. |
ok2Create |
Boolean | (optional) Set true if a label should be created when not found. Default is true. |
Returns
Type | Description |
---|---|
String | ID of Label, or null if not found or created. |
Create Label for given labelName
.
Parameters
Name | Type | Description |
---|---|---|
labelName |
String | Name of label to create. |
Returns
Type | Description |
---|---|
String | ID of Label. |