Arshad Chummun

Programming Ramblings

Contact Form in Octopress: Making Notifications Awesomer

This is a follow-up of the Contact Form in Octopress. In this post, we’re going to use custom scripts in Google Docs to mail the form values on form submit. Here’s how:

Step 1: Open the spreadsheet for the Google Form built in the previous post.

Step 2: Open the Script Editor (Tools -> Script Editor)

Step 3: Add in a title for the new script. (eg. mailFormValuesOnSubmit)

Step 4: Paste in the following code and save it.

mailFormValuesOnSubmit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function mailFormValuesOnSubmit(e) {
  try {
    var sheet = SpreadsheetApp.getActiveSheet();
    var sheetName = sheet.getParent().getName();

    var x = sheet.getLastRow();
    var y = sheet.getLastColumn();
    var values = sheet.getRange(x, 1, x, y).getValues();

    //email values
    var recipient = "INSERT_EMAIL_HERE";
    var name = values[0][1];
    var email = values[0][2];
    var subject = sheetName + ": " + values[0][3];
    var message = "From: " + name +" (" + email + ")\n\n";
    message += values[0][4];

    //send the email
    MailApp.sendEmail(recipient, subject, message);
  } catch(e){
    MailApp.sendEmail(recipient, sheetName + ": Error", sheetName + ": Error");
  }
}

The code above will get the values of the last row and mail it to the recipient email address provided. My form has name, email, subject and message fields. So I’m using this code to mail me the values with the name, email and message in the email body. You can customize the subject and message to send. The values variable is a 2d array indexed by row number then by column number. So the following code returns the value of the first row and third column, which in my case here is email.

1
var email = values[0][2]];

Now that our script is saved, we need to tell the spreadsheet to run this script on form submit. We’ll use a trigger.

Step 5 : Under Resources, Click on “Current Script’s triggers”. Add a new trigger : Run mailFormValuesOnSubmit From Spreadsheet On Form Submit. Save.

Now, when you submit your form, you should get the values submitted in an email right away.

That’s it, contact form awesomeness in Octopress.