Editor’s note: If you’re in the SF area, join us tomorrow for our next hackathon. There are a few spots left. See Eric's note at the end of this post.
Last Thursday’s Google Apps Hackathon in New York brought together 70 developers to create cool new applications using Google Apps APIs. The varied field of talent included individual developers, small teams from companies like ShuttleCloud, and a group of technically inclined educators from the non-profit New Visions for Public Schools.
Ten Google engineers were on hand to help participants with tips and information about specific APIs. Among them, Dan Holevoet and Alain Vongsouvanh from Mountain View shared their Calendar and Contacts API expertise, while Shradda Gupta and Gunjan Sharma traveled from India to help field questions about admin and domain management APIs.
At this hackathon, competitors had two categories to choose from: building new applications using Google Apps APIs, and integrating Google Apps APIs with an existing app. The various groups entered and demonstrated a total of sixteen apps across the two categories, including:
For the new apps category, the panel of judges settled first prize on “AlphaSheet,” a simple but streamlined app using a custom spreadsheet function to fill in values from Wolfram Alpha queries. “Fareshare” took top honors in the second category for integrating Google Calendar in a mobile app that helps New Yorkers share cab rides.
It’s great to see developers join forces and have a great time hacking up new apps at events like this one. An impressive amount of knowledge-sharing occurred, and everyone walked away with new ideas and skills to take back to their work in the realms of business or education.
If you missed this event, don’t worry — the future holds more hackathons, including the upcoming event tomorrow (Dec 6th) at Google’s Mountain View, CA campus from 1:00pm - 8:00pm PST. If you’re located in Europe, we have a series of events planned over the next few months.
Yesterday, the Google APIs Client Library for JavaScript was released, unlocking tons of possibilities for fast, dynamic web applications, without requiring developers to run their own backend services to talk to Google APIs. This client library supports all discovery-based APIs, including the Google Tasks, Google Calendar v3 and Groups Settings APIs. To make it easy to get started using the JS client with Google Apps APIs, we’ve provided an example below.
After you’ve configured your APIs console project as described in the client library instructions, grab a copy of your client ID and API key, as well as the scopes you need to access the API of your choice.
var clientId = 'YOUR_CLIENT_ID'; var apiKey = 'YOUR_API_KEY'; var scopes = 'https://www.googleapis.com/auth/calendar';
You’ll also need several boilerplate methods to check that the user is logged in and to handle authorization:
function handleClientLoad() { gapi.client.setApiKey(apiKey); window.setTimeout(checkAuth,1); checkAuth(); } function checkAuth() { gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult); } function handleAuthResult(authResult) { var authorizeButton = document.getElementById('authorize-button'); if (authResult) { authorizeButton.style.visibility = 'hidden'; makeApiCall(); } else { authorizeButton.style.visibility = ''; authorizeButton.onclick = handleAuthClick; } } function handleAuthClick(event) { gapi.auth.authorize( {client_id: clientId, scope: scopes, immediate: false}, handleAuthResult); return false; }
Once the application is authorized, the makeApiCall function makes a request to the API of your choice. Here we make a request to retrieve a list of events from the user’s primary calendar, and use the results to populate a list on the page:
function makeApiCall() { gapi.client.load('calendar', 'v3', function() { var request = gapi.client.calendar.events.list({ 'calendarId': 'primary' }); request.execute(function(resp) { for (var i = 0; i < resp.items.length; i++) { var li = document.createElement('li'); li.appendChild(document.createTextNode(resp.items[i].summary)); document.getElementById('events').appendChild(li); } }); }); }
To tie all of this together, we use the following HTML, which configures the DOM elements we need to display the list, a login button the user can click to grant authorization, and a script tag to initially load the client library:
<html> <body> <div id='content'> <h1>Events</h1> <ul id='events'></ul> </div> <a href='#' id='authorize-button' onclick='handleAuthClick();'>Login</a> <script> // Insert the JS from above, here. </script> <script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script> </body> </html>
Making requests to other discovery-based APIs, such as the Tasks API requires only small modifications to the above:
As additional discovery-based APIs are released, they’ll be automatically supported by the library (just like the Python and Ruby clients).
If you have general questions about the JS client, check out the JavaScript client group. For questions on specific Apps APIs come find us in the respective Apps API forum.
One of the big focuses of this blog (and the team behind it) has been providing compelling examples of how integration with Google Apps APIs can make a product richer and more engaging. As a part of this effort, earlier today we announced Au-to-do, a sample application built using Google APIs.
Au-to-do is a sample implementation of a ticket tracker, built using a combination of Google App Engine, Google Cloud Storage, and Google Prediction APIs.
In addition to providing a demonstration of the power of building on Google App Engine, Au-to-do also provides an example of improving the user experience by integrating with Google Apps. Users of Au-to-do can automatically have tasks created using the Google Tasks API whenever they are assigned a ticket. These tasks have a deep link back to the ticket in Au-to-do. This helps users maintain a single todo list, using a tool that’s already part of the Google Apps workflow.
We’re going to continue work on Au-to-do, and provide additional integrations with Google Apps (and other Google APIs) in the following months.
To learn more, read the full announcement or jump right to the getting started guide.
Google Apps domain administrators can programmatically create and manage users, groups, nicknames and organization units using the Provisioning API.
Support for OAuth 2.0 in the Provisioning API allows Google Apps domain administrators to authorize access to the API without sharing their passwords. After the administrator agrees to grant access, an OAuth 2.0 token makes sure that an application gets access to the right scope of resources for API calls.
We have recently added a new sample to the Python client library to demonstrate authorization with OAuth 2.0 for an application combining the Provisioning API and the Email Settings API. This sample app iterates through each user on a domain and creates an e-mail filter to mark all messages from outside the domain as “read.” For a step-by-step walkthrough of the sample, have a look at our new article: OAuth 2.0 with the Provisioning and the Email Settings API.
We would be glad to hear your feedback or any questions you have on the Google Apps Domain Info and Management APIs forum.
Google Apps domain administrators can use the Email Audit API to download mailbox accounts for audit purposes in accordance with the Customer Agreement. To improve the security of the data retrieved, the service creates a PGP-encrypted copy of the mailbox which can only be decrypted by providing the corresponding RSA key.
When decrypted, the exported mailbox will be in mbox format, a standard file format used to represent collections of email messages. The mbox format is supported by many email clients, including Mozilla Thunderbird and Eudora.
If you don’t want to install a specific email client to check the content of exported mailboxes, or if you are interested in automating this process and integrating it with your business logic, you can also programmatically access mbox files.
You could fairly easily write a parser for the simple, text-based mbox format. However, some programming languages have native mbox support or libraries which provide a higher-level interface. For example, Python has a module called mailbox that exposes such functionality, and parsing a mailbox with it only takes a few lines of code:
import mailbox def print_payload(message): # if the message is multipart, its payload is a list of messages if message.is_multipart(): for part in message.get_payload(): print_payload(part) else: print message.get_payload(decode=True) mbox = mailbox.mbox('export.mbox') for message in mbox: print message['subject'] print_payload(message)
Let me know your favorite way to parse mbox-formatted files by commenting on Google+.
For any questions related to the Email Audit API, please get in touch with us on the Google Apps Domain Info and Management APIs forum.
The Google Calendar API is one of Google’s most used APIs. Today, we’re rolling out a new version of the API that will give developers even more reasons to use it. Version three of the Google Calendar API provides several improvements over previous versions of the API:
Developers familiar with the Google Tasks API will feel right at home with Calendar API v3, as it uses similar syntax and conventions, as well as the same base client libraries. These Google-supported client libraries, based on discovery, are available in many languages with:
If you’re new to the Google Calendar API, getting started is easy. Check out the Getting Started Guide, which will walk you through the basic concepts of Google Calendar, the API, and authorization. Once you’re ready to start coding, the Using the API page will explain how to download and use the client libraries in several languages.
If you’d like to try out some queries before you start coding, check out the APIs Explorer and try out some example queries with the new API.
Developers already using older versions of the API can refer to our Migration Guide. This interactive guide offers side-by-side examples of the API in v2 and v3 flavors across both the protocol and multiple languages. Simply hover over the code in v2 (or v3) and see the equivalent in the other version.
With our announcement of v3 of the API, we’re also announcing the deprecation of the previous versions (v1 and v2). The older versions enter into a three year deprecation period, beginning today, and will be turned off on November 17, 2014.
We’d love to hear your feedback on the Google Calendar API v3. Please feel free to reach out to us in the Google Calendar API forum with any questions or comments you have. We’ll also be hosting live Office Hours (via Google+ Hangout) on 11/30 from 8am-8:45am EST to discuss the new API. We hope to see you then!
When it comes to writing UI applications in Apps Script, we get a lot of requests to support event callbacks that are handled in the user’s browser. For example, if your application has a form, you may want to disable a button after it is clicked the first time. Until now, the only way to do that would be by using an event handler on the server to disable that button. Using Client Handlers, your application can now respond to events in the browser without the need to perform a round trip to Google Apps Script servers.
By cutting out the round trip to the server, your app can respond instantly to user input. Imagine, for example, you want to provide your users with instant feedback within your app when a user types text where a number is expected. Ideally, you would want to warn users as they type the value, instead of waiting until the form is submitted. Having a server event handler for each keystroke is definitely overkill for such a simple and common task. Luckily, these use cases are now supported with Apps Script’s new Client Handlers and validators!
Let’s take a look at some code.
A Client Handler allows you to react to any event in a browser without connecting to the server. What you can do in response to an event is limited to a set of predefined common actions, but you have a lot of flexibility in making your app more responsive.
You can use Client Handlers in any UiApp regardless of whether you are embedding in a Spreadsheet or a Sites Page or publishing as a service. This simple application enables the user to click a button to display the classic “Hello world” message:
function doGet() { var app = UiApp.createApplication(); var button = app.createButton("Say Hello"); // Create a label with the "Hello World!" text and hide it for now var label = app.createLabel("Hello World!").setVisible(false); // Create a new handler that does not require the server. // We give the handler two actions to perform on different targets. // The first action disables the widget that invokes the handler // and the second displays the label. var handler = app.createClientHandler() .forEventSource().setEnabled(false) .forTargets(label).setVisible(true); // Add our new handler to be invoked when the button is clicked button.addClickHandler(handler); app.add(button); app.add(label); return app; }
The Client Handlers in the above example are set up in two steps:
forTargets
forEventSource
In the above example, we set the handler’s target to be the event source, so that it will apply to the button that is clicked. Finally, we define the action that the handler should take, in this case disabling the button using setEnabled(false). Aside from setEnabled, you can also change styles using setStyleAttribute, change text using setText, and so on. One Client Handler can perform multiple actions — just chain them together - and you can even change the target so that some actions apply to one set of widgets and some actions to another set. In our example, along with disabling the button, we set the handler to display the label when it is invoked, using setVisible.
setEnabled(false)
setEnabled
setStyleAttribute
setText
setVisible
Another new addition to Apps Script is support for validators in handlers. Validators allow handlers to check simple and complex conditions before they are invoked. For example, the following application adds two numbers given by the user, while using validators to make sure the server is only called if both of the text boxes contain numbers.
function doGet() { var app = UiApp.createApplication(); // Create input boxes and button var textBoxA = app.createTextBox().setId('textBoxA').setName('textBoxA'); var textBoxB = app.createTextBox().setId('textBoxB').setName('textBoxB'); var addButton = app.createButton("Add"); // Create a handler to call the adding function // Two validations are added to this handler so that it will // only invoke 'add' if both textBoxA and textBoxB contain // numbers var handler = app.createServerClickHandler('add') .validateNumber(textBoxA) .validateNumber(textBoxB) .addCallbackElement(textBoxA) .addCallbackElement(textBoxB); addButton.addClickHandler(handler) app.add(textBoxA); app.add(textBoxB); app.add(addButton); return app; } function add(e) { var app = UiApp.getActiveApplication(); var result = parseFloat(e.parameter.textBoxA) + parseFloat(e.parameter.textBoxB); var newResultLabel = app.createLabel("Result is: " + result); app.add(newResultLabel); return app; }
There’s a variety of validators to choose from that perform different tasks. You can verify the input to be a number, an integer, or an e-mail address. You can check for a specific length, or for any numerical value in a defined range. You can also use general regular expressions. Lastly, each validator has its negation.
Note that validators work with both client and server handlers.
Of course, validators and Client Handlers work best together. For example, in our addition application above, the “Add” button should be disabled as long as the current input is not numeric. We would also like to let the user know why the button is disabled by displaying an error message. To do so, we combine the power of server handlers, Client Handlers, and validators in the following way:
function doGet() { var app = UiApp.createApplication(); // Create input boxes and button. var textBoxA = app.createTextBox().setId('textBoxA').setName('textBoxA'); var textBoxB = app.createTextBox().setId('textBoxB').setName('textBoxB'); var addButton = app.createButton("Add").setEnabled(false); var label = app.createLabel("Please input two numbers"); // Create a handler to call the adding function. // Two validations are added to this handler so that it will // only invoke 'add' if both textBoxA and textBoxB contain // numbers. var handler = app.createServerClickHandler('add') .validateNumber(textBoxA) .validateNumber(textBoxB) .addCallbackElement(textBoxA) .addCallbackElement(textBoxB); // Create handler to enable the button well all input is legal var onValidInput = app.createClientHandler() .validateNumber(textBoxA) .validateNumber(textBoxB) .forTargets(addButton).setEnabled(true) .forTargets(label).setVisible(false); // Create handler to mark invalid input in textBoxA and disable the button var onInvalidInput1 = app.createClientHandler() .validateNotNumber(textBoxA) .forTargets(addButton).setEnabled(false) .forTargets(textBoxA).setStyleAttribute("color", "red") .forTargets(label).setVisible(true); // Create handler to mark the input in textBoxA as valid var onValidInput1 = app.createClientHandler() .validateNumber(textBoxA) .forTargets(textBoxA).setStyleAttribute("color", "black"); // Create handler to mark invalid input in textBoxB and disable the button var onInvalidInput2 = app.createClientHandler() .validateNotNumber(textBoxB) .forTargets(addButton).setEnabled(false) .forTargets(textBoxB).setStyleAttribute("color", "red") .forTargets(label).setVisible(true); // Create handler to mark the input in textBoxB as valid var onValidInput2 = app.createClientHandler() .validateNumber(textBoxB) .forTargets(textBoxB).setStyleAttribute("color", "black"); // Add all the handlers to be called when the user types in the text boxes textBoxA.addKeyUpHandler(onInvalidInput1); textBoxB.addKeyUpHandler(onInvalidInput2); textBoxA.addKeyUpHandler(onValidInput1); textBoxB.addKeyUpHandler(onValidInput2); textBoxA.addKeyUpHandler(onValidInput); textBoxB.addKeyUpHandler(onValidInput); addButton.addClickHandler(handler); app.add(textBoxA); app.add(textBoxB); app.add(addButton); app.add(label); return app; } function add(e) { var app = UiApp.getActiveApplication(); var result = parseFloat(e.parameter.textBoxA) + parseFloat(e.parameter.textBoxB); var newResultLabel = app.createLabel("Result is: " + result); app.add(newResultLabel); return app; }
All of these features can be used to create more advanced and responsive applications. Client handlers can be used to change several attributes for widgets, and validators can help you check a variety of different conditions from well formed email addresses to general regular expressions.
If you'd like to chat about these new features or have other questions about Google Apps Script, please join several members of the Apps Script team in the Google Apps Developer Office Hours on Google+ Hangouts tomorrow, Wednesday November 16th at 10am PST. You can also ask questions at any time in the Apps Script forum.
We are very excited to invite all Google Apps developers to our upcoming round of hackathons! We are hosting the hackathons at our Mountain View, CA campus, and at our New York City campus.
The hackathons enable teams of developers to build something integrating the Google experience into a product. Come to the hackathons for fun, food, and the experience. Increase your knowledge of the Google Apps developer platform, while also building something really cool. Meet other developers, Google engineers, and share stories of your integrations and experience. We are handing out prizes for the best projects, including the best new projects, and the best integrations into existing projects -- more details, including the rules and prizes, will be sent out to registrants soon. Don’t worry if you don’t have a team or an existing project-- impromptu teams are great!
Specific details of each event follow. Space is limited, so make sure to register as soon as possible. Confirmation emails are sent to accepted registrants.
Google Apps Developer Hackathon, NYC Click here to register Thursday, December 1, 2011 1:00pm - 8:00pm EST Google NYC 111 8 Ave. New York, NY 10011
Google Apps Developer Hackathon, Mountain View Click here to register Tuesday, December 6, 2011 1:00pm - 8:00pm PST Google 1300 Crittenden Lane Mountain View, CA
Drinks, after-lunch snacks, and dinner will be provided. Please bring your laptop. Power and wireless internet access will also provided.
If you’re a Google Apps administrator and you want to create multiple Google Groups for your domain, you can do so using the Google Apps Provisioning API. However, until today, there was no way for you to programmatically update the settings for the groups you created. Some organizations have hundreds or even thousands of groups, and you’ve told us that you want a more streamlined method for managing these groups’ settings. That’s why we’re pleased to announce the Google Apps Groups Settings API, which allows you to control settings for all of your groups much more efficiently.
The Google Apps Groups Settings API is available for Google Apps for Business, Education and ISPs and can be used to manage:
To begin using the Google Groups Settings API today, follow the instructions in the API documentation. You will need to sign in to the Google APIs Console and request access to the API. We hope the API will allow you to more quickly and easily manage all of the groups in your domain. If you have any questions about this API, please ask them in the Domain Information and Management APIs forum.
Editor's note: This has been cross-posted from the Google Code blog -- Ryan Boyd
In March, we announced that all of the Google Web APIs adopted support for OAuth 2.0. It is the recommended authorization mechanism when using Google Web APIs.
Today, we are announcing the OAuth 2.0 Playground, which simplifies experimentation with the OAuth 2.0 protocol and APIs that use the protocol. Trying out some requests in the OAuth 2.0 playground can help you understand how the protocol functions and make life easier when the time comes to use OAuth in your own code.
Selecting the APIs to authorize
With the OAuth 2.0 Playground, you can walk through each step of the OAuth 2.0 flow for server-side web applications: authorizing API scopes (screen shot above), exchanging authorization tokens (screen shot below), refreshing access tokens, and sending authorized requests to API endpoints. At each step, the Playground displays the full HTTP requests and responses.
The OAuth Playground can also use custom OAuth endpoints in order to test non-Google APIs that support OAuth 2.0 draft 10.
OAuth configuration screen
You can click the link button to generate a link to a specific Playground state. This allows quick access to replay specific requests at a later time.
Generating a deep link to the playground’s current state
Please feel free to try the OAuth 2.0 Playground. We are happy to receive any feedback, bugs, or questions in the OAuth Playground forum.
Two weeks ago, we had our inaugural Office Hours on Google+ Hangouts, bringing together Google Apps developers from the UK, Ireland, Russia, Brazil, Germany and the US to chat. Everyone asked great questions and provided feedback on many of the APIs. It was also exciting that Google+ for Google Apps was announced at the same time as our hangout.
Given the strong interest in these Office Hours, we’re going to continue doing Hangouts with the Google Apps developer community. Some will be general Hangouts where all types of questions related to the Google Apps APIs will be welcome. Others will be focused on individual products and include core software engineers and product managers who are building the APIs you love.
Here’s the next couple: Tomorrow, November 8th @ 11:30am PST (General Office Hours) November 16th @ 10am PST (Google Apps Script team)
We’ll continue adding more Office Hours on the events calendar, and announce them on @GoogleAppsDev and our personal Google+ profiles.
Hope you’ll hang out with us soon!
The OAuth Playground is a great tool to learn how the OAuth flow works. But at the same time it can be used to generate a "long-lived" access token that can be stored, and used later by applications to access data through calls to APIs. These tokens can be used to make command line tools or to run batch jobs.
In this example, I will be using this token and making calls to the Google Provisioning API using the Python client library for Google Data APIs. But the following method can be used for any of the Google Data APIs. This method requires the token is pushed on the token_store, which is list of all the tokens that get generated in the process of using Python client libraries. In general, the library takes care of it. But in cases where it’s easier to request a token out of band, it can be a useful technique.
token_store
Step 1: Generate an Access token using the OAuth Playground. Go through the following process on the OAuth Playground interface:
consumer_key
consumer_secret
After entering all the required details you need to press these buttons on the OAuth Playground in sequence:
After the last step the text field captioned auth_token in the OAuth Playground has the required Access token and that captioned access_token_secret has the corresponding token secret to be used later.
Step 2: Use the above token when making calls to the API using a Python Client Library.
Here is an example in Python which uses the OAuth access token that was generated from OAuth Playground to retrieve data for a user.
CONSUMER_KEY = “CONSUMER_KEY” CONSUMER_SECRET = “CONSUMER_SECRET” SIG_METHOD = gdata.auth.OAuthSignatureMethod.HMAC_SHA1 TOKEN = “GENERATED_TOKEN_FROM_PLAYGROUND” TOKEN_SECRET = “GENERATED_TOKEN_SECRET_FROM_PLAYGROUND” DOMAIN = “your_domain” client = gdata.apps.service.AppsService(source=”app”, domain=DOMAIN) client.SetOAuthInputParameters(SIG_METHOD, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET) temp_token = gdata.auth.OAuthToken(key=TOKEN, secret=TOKEN_SECRET); temp_token.oauth_input_params = client.GetOAuthInputParameters() client.SetOAuthToken(temp_token) #Make the API calls user_info = client.RetrieveUser(“username”)
It is important to explicitly set the input parameters as shown above. Whenever you call SetOuthToken it creates a new token and pushes it into the token_store. That becomes the current token. Even if you call SetOauthToken and SetOAuthInputParameters back to back, it won’t set the input params for the token you set.
SetOuthToken
SetOauthToken
SetOAuthInputParameters
You can use the long-lived token to make command line requests, for example using cURL. It can be useful when you need to counter-check bugs in the client library and to test new features or try to reproduce issues. In most cases, developers should use the client libraries as they are designed, as in this example.
Sometimes you want to cache data in your script. For example, there’s a RSS feed you want to use and a UiApp that you’ve built to view and process the feed. Up until now, each operation to work on the feed would require re-fetching the feed, which can get slow.
UiApp
Enter the newly launched CacheService which will allow for caching resources between script executions. Like the recently announced LockService, there are two kinds of caches: a public cache that is per-script, and a private cache which is per-user, per-script. The private cache should be used to store user-specific data, while the public cache is used to store strings that should be accessible no matter who calls the script.
So for our example feed viewer/processor, you’d already have a function to retrieve and process the feed. In order to use the CacheService, you’d wrap it like this:
function getFeed() { var cache = CacheService.getPublicCache(); var value = cache.get(“my rss feed”); if (value == null) { // code to fetch the contents of the feed and store it in value // here (assumes value is a string) // cache will be good for around 3600 seconds (1 hour) cache.put(“my rss feed”, value, 3600); } return value; }
The cache doesn’t guarantee that you won’t have to fetch it again sooner, but will make a best effort to retain it for that long, and expire it quickly after the time passes. Now you can call getFeed() often and it won’t re-fetch the feed from the remote site on each script execution, resulting in improved performance.
getFeed()
Check out the CacheService documentation for more information.
Here’s the scenario: you create a form, you have a script that triggers onFormSubmit and all is well... until it gets popular. Occasionally you start having interlacing modifications from separate invocations of your script to the spreadsheet. Clearly, this kind of interlacing is not what you intended for the script to do. Up until now, there was no good solution to this problem -- except to remain unpopular or just be lucky. Neither are great solutions.
onFormSubmit
Now, my friend, you are in luck! We’ve just launched the LockService to deal with exactly this problem. The LockService allows you to have only one invocation of the script or portions thereof run at a time. Others that would’ve run at the same time can now be made to wait nicely in line for their turn. Just like the line at the checkout counter.
The LockService can provide two different kinds of locks-- one that locks for any invocation of your script, called a public lock, and another that locks only invocations by the same user on your script, called a private lock. If you’re not sure, using a public lock is the safest bet.
For example, in the scenario in the previous paragraph you would want something like this:
function onFormSubmit() { // we want a public lock, one that locks for all invocations var lock = LockService.getPublicLock(); lock.waitLock(30000); // wait 30 seconds before conceding defeat. // got the lock, you may now proceed ...whatever it used to do here.... lock.releaseLock(); }
It’s best to release the lock at the end, but if you don’t, any locks you hold will be released at the end of script execution. How long should you wait? It depends on two things mainly: how long the thing you’re going to do while holding the lock takes, and how many concurrent executions you expect. Multiply those two and you’ll get your timeout. A number like 30 seconds should handle a good number of cases. Another way to pick the number is frankly to take an educated guess and if you guess too short, the script will occasionally fail.
If you want to avoid total failure if you can’t get the lock, you also have the option trying to get the lock and doing something else in the event of not being able to get it:
function someFunction() { var lock = LockService.getPublicLock(); if (lock.tryLock(30000)) { // I got the lock! Wo000t!!!11 Do whatever I was going to do! } else { // I couldn’t get the lock, now for plan B :( GmailApp.sendEmail(“admin@example.com”, “epic fail”, “lock acquisition fail!”); } }
So now your scripts can be as popular as they can get with no worries about messing up shared resources due to concurrent edits! Check out the LockService documentation for more information.
We are currently rolling out a change to the organization of existing resources in collections in Google Docs. This change is completely transparent to users of the Google Docs web user interface, but it is technically visible when using the Google Documents List API to make requests with the showroot=true query parameter or specifically querying the contents of the root collection. In order to understand this change, first read how Google Docs organizes resources.
showroot=true
The change involves Google removing those resources from a user’s root collection that already exist within another collection accessible to the given user. That is, if “My Presentation” is currently in root and in the “My Talks” collection, after this change it will only exist in the “My Talks” collection.
We are making this change in order to make the organization of resources less confusing for API developers. This change allows clients to know that a resource either exists in root or in some collection under root. Clients can still retrieve all resources, regardless of which collections they’re in, using the resources feed.
The change is rolling out gradually to all Google Docs users over the next few months.
Developers with further questions about this change should post in the Google Documents List API forum.
Update (August 2014): Try the Yet Another Mail Merge add-on for Google Sheets.
Editor’s Note: This blog post is co-authored by James, Steve and Romain who are Google Apps Script top contributors. -- Ryan Boyd
The Google Apps Script team is on a roll and has implemented a ton of new features in the last few months. Some of us “Top Contributors” thought it will be a useful exercise to revisit the Mail Merge use case and discuss various ways in which we can do Mail Merge using Apps Script. Below are several techniques that tap into the power of Google Apps Script by utilizing Gmail, Documents and Sites to give your mailings some zing. Mail Merge is easy and here is how it can be done.
The Simple Mail Merge tutorial shows an easy way to collect information from people in a Spreadsheet using Google Forms then generate and distribute personalized emails. In this tutorial we learn about using “keys,” like ${"First Name"}, in a template text document that is replaced by values from the spreadsheet. This Mail Merge uses HTML saved in the “template” cell of the spreadsheet as the content source.
${"First Name"}
The Gmail Service is now available in Google Apps Script, allowing you to create your template in Gmail where it is saved as a draft. This gives us the advantage of making Mail Merge more friendly to the typical user who may not know or care much about learning to write HTML for their template. The mail merge script will replace the draft and template keys with names and other information from the spreadsheet and automatically send the email.
To use this mail merge, create a new spreadsheet, and click on Tools > Script Gallery. Search for “Yet another Mail Merge” and you will be able to locate the script. Then, click Install. You’ll get two authorization dialogs, click OK through them. Add your contact list to the spreadsheet, with a header for each column. Then compose a new mail in Gmail. Follow this syntax for the “keys” in your template: $%column header% (see above). Click Save now to save your draft. Go back to your spreadsheet and click on the menu Mail Merge. A dialog pops up. Select your draft to start sending your emails.
$%column header%
You can add CCs, include attachments and format your text just as you would any email. People enjoy “Inserting” images in the body of their emails, so we made sure to keep this feature in our updated mail merge. To automate this process we will use a new advanced parameter of the method sendEmail, inlineImages. When the script runs it looks in the email template for images and make sure they appear as inline images and not as attachments. Now your emails will look just as you intended and the whole process of mail merge got a whole lot simpler.
sendEmail
inlineImages
The next Mail Merge will use a template that is written in a Google Document and sent as an attachment. Monthly reports, vacation requests and other business forms can use this technique. Even very complex documents like a newsletter or brochure can utilize the automation of Google Apps Script to add the personal touch of having your patron’s name appear as a salutation.
Like in the Mail Merge for Gmail, the Google Docs template will use “keys” as placeholders for names, addresses or any other information that needs to be merged. Google Apps Script can add dynamic elements as well. For example you may want to include a current stock quote using the Financial Service, a chart from the Charts Service, or a meeting agenda automatically fetched for you by the Calendar Service.
As the code sample below demonstrates, the Google Apps Script gets the document template, copies it in a new temporary document, opens the temp document, replaces the key placeholders with the form values, converts it to PDF format, composes the email, sends the email with the attached PDF and deletes the temp document.
Here is a code snippet example to get you started. To use this mail merge, create a new spreadsheet, and click on Tools > Script Gallery. Search for “Employee of the Week Award” and you will be able to locate the script.
// Global variables docTemplate = “enter document ID here”; docName = “enter document name here”; function sendDocument() { // Full name and email address values come from the spreadsheet form var full_name = from-spreadsheet-form var email_address = from-spreadsheet-form // Get document template, copy it as a new temp doc, and save the Doc’s id var copyId = DocsList.getFileById(docTemplate) .makeCopy(docName+' for '+full_name) .getId(); var copyDoc = DocumentApp.openById(copyId); var copyBody = copyDoc.getActiveSection(); // Replace place holder keys, copyBody.replaceText('keyFullName', full_name); var todaysDate = Utilities.formatDate(new Date(), "GMT", "MM/dd/yyyy"); copyBody.replaceText('keyTodaysDate', todaysDate); // Save and close the temporary document copyDoc.saveAndClose(); // Convert temporary document to PDF by using the getAs blob conversion var pdf = DocsList.getFileById(copyId).getAs("application/pdf"); // Attach PDF and send the email MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf}); // Delete temp file DocsList.getFileById(copyId).setTrashed(true); }
For the last example let’s assume you have a great Google Site where you create new letters for your followers. However, you have had some feedback suggest that while many users don’t mind visiting your site, some would prefer to have the newsletter emailed to them. Normally this would require copying and pasting into an email or doc. Why not simply automate this with Google Apps Script?
The body section of a site, the part you edit, can be captured as HTML by the Sites Service and placed in the body of an email. Because the return value is HTML, the pictures and text formatting come through in the email.
Here is a simple example for you to try out:
function emailSiteBody() { var site = SitesApp.getPageByUrl('YourPageURL'); var body = site.getHtmlContent(); MailApp.sendEmail('you@example.com', 'Site Template', 'no html :( ', {htmlBody: body}); }
It really is that simple. Add a for loop with email values from a spreadsheet and this project is done.
for
Happy merging!
Updated 10/28: fixed instructions for accessing the complete script source for solution 3.
Editor's note: This post by Google Senior Product Manager Justin Smith has been cross-posted from the Google Code blog because we think it'll be of great interest to Google Apps developers. -- Ryan Boyd
In the coming weeks we will be making three changes to the experimental OAuth 2.0 endpoint. We expect the impact to be minimal, and we’re emailing developers who are most likely to be affected.
https://www.example.com/back?error=access_denied.
https://www.example.com/back?error=access_denied
https://www.example.com/back#error=access_denied
approval_prompt=force
access_type=offline
https://accounts.google.com/o/oauth2/auth? client_id=21302922996.apps.googleusercontent.com& redirect_uri=https://www.example.com/back& scope=https://www.google.com/m8/feeds/& response_type=code
https://accounts.google.com/o/oauth2/auth? client_id=21302922996.apps.googleusercontent.com& redirect_uri=https://www.example.com/back& scope=https://www.google.com/m8/feeds/& response_type=code& access_type=offline& approval_prompt=force