Google Forms Confirmation Email with Attachments

Google Forms is a great tool to use to make quick and easy sign-up forms, but sometimes you need it to do something else a bit more complex. In this short tutorial we’ll talk about how to extend a basic Google Form script that sends confirmation email to also send attachments. If you don’t know how to send the Google Form confirmation email, check out the first tutorial on that topic here:

Part 1: Sending a Confirmation Email with Google Forms>>>>>

 

Step 1: Get a Google Doc as PDF

The first thing we are going to add to the script will retrieve a Google Doc from your Google Drive App. Create a new variable that accesses the Drive App and gets a particular file by its id.

var file = DriveApp.getFileById("longidstringgoeshere");

You can find the id string of your document by looking in its URL in another tab

Google-Forms-id

 

Now we have created a variable that opens your Drive App and gets a particular file by Id. Next we’re going to tell it specifically what file type we want. We will call some specific methods on the file variable to make that happen. Create a new variable to store our final Drive Doc as a PDF:

var pdfFile = file.getAs(MimeType.PDF);

Ok, this line of code just specifies the document as a PDF for our attachment. In Step 2, we’ll look at how to use this file as an attachment in our mail function.

Step 2: Add Attachment and Send Email from Google Forms

Now that we have our file built using the Drive App, we can add this attachment variable to our mail function so that an attachment is sent when someone submits something in Google Forms. To do this, we add another parameter to our initial mail function like the code example below:

MailApp.sendEmail(email, subject, body, {attachments:[liabilityWaiver]});

 

We are adding the attachment through a JavaScript Object (JSON) that we are passing as an additional parameter. A JSON object is created with curly braces and a number of key:value pairs seperated by commas.

{
attachments:[pdfFile]
}

In this example we use the key of “attachments” which accepts an array as a value. It accepts an array because we could also include multiple files here formatted as a JavaScript array.

{
attachments:[pdfFile, anotherFile, anotherFileStill]
}

After that, you should be ready to save out your code and send an email attachment. Just make sure to check your syntax when ending the mail function line if you get any initial errors.



 

Here is the whole script:

function myFunction(e) {
 var name = e.values[1];
 var phoneNumber = e.values[2];
 var email = e.values[3];
 
 var subject = "Thanks for submitting";
 var body = "We look forward to racing with you. Don't forget to fill out and bring the attached waiver on race day.";
 
 var waiver = DriveApp.getFileById("yourFileIdHere");
 var liabilityWaiver = waiver.getAs(MimeType.PDF);
 
 
 
 MailApp.sendEmail(email, subject, body, {attachments:[liabilityWaiver]}); 
}

Be sure to review Part 1:

Part 1: Sending a Confirmation Email with Google Forms>>>>>

60 thoughts on “Google Forms Confirmation Email with Attachments”

  1. Steven says:

    Would it be possible to create a form and have it automatically send an email confirmation with a PDF but the confirmation is only sent if the a certain field (email) in on another Google sheet and the PDF that is sent is dependent on the date of submission.

    Example.

    I submit the form on 3/17/15 and I receive my confirmation email because my email is part of the membership email list. I receive the PDF that is for 3/18.

    Thanks

    1. admin says:

      Sorry for the late reply, but yes to all things. You are looking for an if statement, which checks a condition, like a date, and then executes some code in this case the mail.app function.

      if (some condition == true) {

      MailApp.sendEmail();
      }

      Post some code below if you have it so I can take a look.

      Regards,
      JE

    2. Wendy says:

      Hi! am going crazy around here, i have the script, its working and everything BUT, what i want is to send the response from “me@mydomain.com” and i just find people saying “yes, if you have the right script you can” but no one post the an example .

      Can you help? i have try a lot of thing and iยดm not so good whit this script things

  2. Tobi says:

    Hi, thanks for this helpful article. But I still have a question.
    The pdf is only attached to the e-mail if the user (who fills out form) doesn’t tick the option “Send me a copy of responses”. How can I send the pdf even if the user ticks that box?

    Thanks so much!

    1. Tobi says:

      Please ignore it, I figured out my mistake.
      Everything works as designed ๐Ÿ™‚

      1. admin says:

        Glad you figured this out!

  3. matt says:

    how do i add new lines in the message body, as at the minute its just a big block of text.
    ta in advance

      1. Matt says:

        Thanks very much, that’s all working now great.

        One other question…. My form now sends its email with attachments to the form filler, but it would be great if it could also send me an email telling me a new entry has been made?
        At the minute I have to keep checking to see if a new entry has been made or not.
        Sounds simple… But I can’t seem to work out how to do it

        1. admin says:

          You can just run the same MailApp method twice, this time to yourself with the subject “Form submitted.”

          1. matt says:

            errrrrrr……
            ok.. how would that look.

            sorry, i have tryd to just duplicate it and just amend the mail address but i have ended up buggering it all up.

            am i supposed to create a whole new seperate script and get the form to run both… or do i add it into the same one?

            any chance you could spell it out for me.. sorry and very much appreciated

          2. admin says:

            Sure thing Matt, please just post the script you have now below and I’ll show you what I mean.

          3. matt says:

            i think i might have worked it out… i think its working. I have to create new email Var’s ect dont i?
            but if you can check then i am grateful

            function myFunction(e){
            var userName = e.values[1];
            var userEmail = e.values[11];
            var date = e.values[0];
            var subject = “Skirfare Bridge Barn booking form succesfully submitted”;
            var message = “Thank you, ” + userName + ” for choosing Skirfare Bridge Barn for your next Yorkshire Adventure. n Please ensure you secure your booking by paying your deposit by bank transfer within 7 days. n All the details are enclosed in the attached copy of the terms and conditions of hire. n n n Best Regards n Matt & Bev n Skirfare Bridge Barn n tel – 07597 645254 n skirfarebridgebarn.co.uk ” ;

            var file = DriveApp.getFileById(“1TRXgLvUmK0Jwbe_J84YxS1zF0zMPnJAtp7tUjdQE_qc”);
            var pdfFile = file.getAs(MimeType.PDF);

            MailApp.sendEmail (userEmail, subject, message, {attachments:[pdfFile]});

            var userEmail2 = “skirfarebridgebarn@gmail.com”;
            var subject2 = “Skirfare Booking Form Submitted”;
            var message2 = + userName + “has just made a booking”;
            MailApp.sendEmail (userEmail2, subject2, message2);
            }

          4. admin says:

            Yup, this should work! Glad you got everything going. Let me know if you have any problems down the road.

            JE

  4. matt says:

    still one thing is driving me mad.

    when i get my email informing me the form has been filled, i get this response “NaNhas just made a booking”

    i dont get the persons username as they filled it in on the form, which in my script looks right to me that it should.

    this last bit is driving me mad.. any help would be great

    1. admin says:

      NaN means not a number in JS. My bet is that the script is pulling in values from a different index. That can happen sometimes if you shift around inputs on a form. Try making a copy and testing that to see if it makes a difference.

      1. JP says:

        Jeff I am getting the same NAN. I’m not sure what you mean by copy it and run it again.

        1. admin says:

          Not sure if this is the same of a different question than the one we talked about on Google+. Let me know if you still need help.

          1. JP says:

            When I get my confirmation email I get this:

            NaNOlsonhas been added to the group.

            Here is the code I’m using. Thank you!!!

            var subject2 = + firstName +athletelastName + ” has been added to the group”;

          2. admin says:

            NaN means not a number. Since you have that plus sign at the beginning of the line of code it is looking for a number in the firstName variable and it finds a string. Try this:
            var subject2 = firstName + ” ” + athletelastName + ” has been added to the group.”;

          3. JP says:

            That got it!!! Thanks Jeff!!

  5. Chris Henry says:

    Great info! Is it possible to send a graphic intense PDF that has been uploaded to Google Drive as a PDF (as opposed to converting a google doc to PDF as shown in the video)? I’ve tried doing it, but not working, here is my code:

    function myFunction(e) {
    var userEmail = e.values[8];
    var subject = “inGauge by TCA Online Demo”;
    var message = “Thanks for completing the survey. PLease see attached”
    var waiver = DriveApp.getFileById(“0B8Dj-4dYh0ZReUtiNnQ1TmM2bGc”);
    var whitePaper = waiver.getAs(MimeType.PDF);

    MailApp.sendEmail(userEmail, subject, message, {attachments: [whitePaper]});

    }

    1. admin says:

      Hmm…I don’t see why not. There is nothing in the docs that would suggest it wouldn’t work. What type of error message are you getting? Or is the email sending without the attachment?

      There is a type in the line with var message; you’re missing a semi-colon. You also might not need to convert the file using getAs since it is already a PDF. Let me know more info about what is happening when you run the script.

      JE

  6. charles says:

    Hello,

    I have tried your approach line by line and word for word but i keek getting this error message

    TypeError: Cannot read property “values” from undefined. (line 2, file “”)

    Help Please

    Regards,

    Charles

    1. admin says:

      Hey Charles,

      Sorry for the delayed reply, but you get that error when running the script in the script editor since there are no values from the event (form submission). Have you tried submitting a test form? If so, and you still get this error, can you post the script here so that I can take a look?
      JE

  7. Hi Thanks for this, I ve set up the script as you described and it works perfectly, I do have one small query though that I hope you can help with. I wanted to send a new form but having the responses for the 2nd form going to a new sheet on the original google doc. I unlinked the first form and went to create a new form from scratch.

    1. admin says:

      When you create the form, or any time thereafter, you can change the response destination. If you click on responses in the form menu there should be an option to change the response destination.

  8. Brett says:

    How do I do a carriage return to create a new line in the plain text email using the script above as a template?

    Thank you.

    1. admin says:

      n is the new line character in JS when put inside a string.

  9. oliv says:

    thankyou for this info,

    btw how do I make a PDF option in google form, so when the audience choose 1 from the option they will get the PDF according to their chosen?

    thankyou and please replay

    1. admin says:

      Oh, good question. If you created a dropdown option that contained say “PDF” and “DOCX” for example, you could check this value and create the blob differently based on the answers.

  10. JP says:

    Jeff thanks so much for the tutorial. I’ve run in to snag on this. Here is my code:

    function confirmationEmail(e) {
    var athletelastName = e.values[1];
    var athletefirstName = e.values[2];
    var primaryEmail = e.values[9];
    var waiver = DriveApp.getFilesByName(“TD Waivers PDF”);
    var subject = “Welcome to the Group!!!”;
    var body = “Thanks for registering ” + athletefirstName + ” for the Group. Please print the attached waiver. Sign, scan, and email it back to us if you have not done so already. Thanks!!!”;

    MailApp.sendEmail(primaryEmail, subject, body, {attachments:[waiver]});

    I set the trigger to run on form submit. When I run a test form submission with my email in it I am not getting the email. Not sure what I’m doing wrong. Thanks!!!

    }

  11. Sid says:

    How to verify an email address that it’s real or not using google forms???

    1. admin says:

      You can turn on data validation for certain inputs. Check out the docs here: https://support.google.com/docs/answer/3378864?hl=en

  12. metin cetin (prof) says:

    Can you help me with this code please.
    I am making a test online. and I want the testers get their result on their emails.
    here is the script

    // This constant is written in column D for rows for which an email
    // has been sent successfully.
    var EMAIL_SENT = “EMAIL_SENT”;

    function sendEmails2() {
    var sheet = SpreadsheetApp.getActiveSheet();
    var startRow = 2; // First row of data to process
    var numRows = 5; // Number of rows to process
    // Fetch the range of cells A2:C20
    var dataRange = sheet.getRange(startRow, 1, numRows, 5)
    // Fetch values for each row in the Range.
    var data = dataRange.getValues();
    for (var i = 0; i -1)
    sh.getRange(‘U2:AJ2’).copyTo(sh.getRange(‘U3:AJ20’));
    })
    } }
    }

    1. metin cetin (prof) says:

      sorry but I think I forgot the secondary part
      ………..

      // This constant is written in column D for rows for which an email
      // has been sent successfully.
      var EMAIL_SENT = “EMAIL_SENT”;

      function sendEmails2() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var startRow = 2; // First row of data to process
      var numRows = 5; // Number of rows to process
      // Fetch the range of cells A2:C20
      var dataRange = sheet.getRange(startRow, 1, numRows, 5)
      // Fetch values for each row in the Range.
      var data = dataRange.getValues();
      for (var i = 0; i -1)
      sh.getRange(‘U2:AJ2’).copyTo(sh.getRange(‘U3:AJ20’));
      })
      } }
      }

      1. admin says:

        Hmmm….what is happening now? Some sort of error I presume?

        I can see that your for loop is missing an argument, but ultimately without knowing more about the structure of the data, I’m not sure that I can help. To get all of the values in a two-dimensional array, try using these lines:

        var range = sheet.getActiveRange(); 
        var values = range.getValues(); 
        for (var i=0; i < values.length; i ++){
        //this gets tricky since we need to look at two indicies
        //the first index is for the row. Second index for column
        var col0 = values[i][0];
        
        } 
        
        
        1. metin cetin says:

          metin cetin (prof)

          Sorry but I am not very good at scripts at all.

          here is my form: https://goo.gl/phLI55
          and here is the spreadsheet : https://goo.gl/J7qGDE
          what I want is: after my students have finished the test, I want the test to be evaluated and the results are sent to the submitters’ emails. Could you help me fix this?

          so far with this script I can evaluate the test and result emails are sent to the emails but the result area is
          “undefined”. besides this script will not write whether the submitter has been sent before or not. Since I am new at scripts, I don’t know which script functions better for my request? Could you help me please?
          the working script but no result is sent:

          function myFunction(e) {
          var firstName = e.values[1];
          var lastName = e.values[0];
          var userEmail = e.values[2];
          var code = Math.floor((Math.random() * 9999) + 1000);
          var subject = “Revision Submission Confirmation Code”;
          var message = “Thanks ” + firstName + ” for KILLING THE CAT. YOU ARE IMPRISONED. YOUR CELL number is ” + code;

          MailApp.sendEmail (userEmail, subject, message);
          }

          function copyBToA() {
          SpreadsheetApp.getActive()
          .getSheets()
          .forEach(function (sh) {
          if(sh.getName().indexOf(‘Form’) > -1)
          sh.getRange(‘G2:L2’).copyTo(sh.getRange(‘G3:L20’));
          })
          }

          1. admin says:

            I’ll take a look an see what advice I can provide. It may be a few days though, I have a busy week ahead ๐Ÿ™‚

  13. Anh says:

    I want when user make survey and click submit, email will auto send to user’email + attach file (servey result of user)

    1. admin says:

      You would just need to first create the file in Drive, populate that file with the user answers and then send it to them the same way I talk about in this video.

  14. Alexander says:

    Hi,

    I’ve used part 1 and it works fantastically thank you. Rather than using this to send out to other people who fill in the form I’m using it so they can send me an email in the correct format. There are two things I’d like to achieve and was hoping you can help me.

    First:
    I’d like the person filling in the form to be given an option to upload an image which will come with the email sent by the script as an attachment. I can seem to find how to do this.

    Secondly:
    The email that comes is in a the standard text format, is it possible to change the font and style that the email is sent with.

    Any help will be greatly appreciated. Thank you.

    1. admin says:

      I haven’t yet figured out a way to have users upload an image. There have been a few people before to ask for that, so I’ll keep it under consideration for a future tutorial.

      You can send a styled HTML email instead of plain text using GmailApp.sendEmail() instead of MailApp.sendEmail(). Check out the official docs here: https://developers.google.com/apps-script/reference/gmail/gmail-app#sendEmail(String,String,String,Object)

      It’s best practice to always send a plain text version in case the device doesn’t display HTML. Thanks for reading/watching! Hope that helps get you started.

  15. francesco says:

    Hello you can attach a .rar file instead of a .pdf file ?

    1. admin says:

      Doesn’t look like the .rar is a supported MIME type in Google Apps Script: https://developers.google.com/apps-script/reference/base/mime-type

      You might try just using the first step, get file by id, and see if that works. Otherwise, you might need to zip it. Let me know how that works out.

  16. Leena says:

    I am trying to get a form to email a notification with a google doc attached please could you help your video is very useful but just cant get a notification with a google doc attached would be really greatful if you could help.

    1. admin says:

      Post the code you have and the error you are getting and I’ll take a look.

      1. Leena says:

        function myfunction(e){
        var name=e.values[4];
        var form=e.values[2];
        var refemail=e.values[3];
        var subject=”Senior Prefect Application”;
        var message=”please fill in reference for +name”

        var waiver=driveapp.getfilebyID(“1T-LjVza7Rcx6Ucp61PssWmqmZQNzIMGdA6vpP4hcjvg”);
        var liabilitywaiver=waiver.getAs(mimeType.google_apps.document);

        mailapp Sendemail(refemail,subject,message[attachments[liabilitywaiver]});

        1. admin says:

          Ok, what error are you getting when this runs?

          I’m also seeing a lot of syntax errors here on line 6, 7, and 8. For example, driveapp should be DriveApp. Similar with getFileById and MailApp and sendEmail. My recommendation is to use the autocomplete that Google Apps Script gives you. Start typing the line on a new line, and Google Apps should give you hints about the correct way to spell some of these functions. Post back if you still have issues.

      2. Leena says:

        function myfunction(e){
        var name=e.values[4];
        var form=e.values[2];
        var refemail=e.values[3];
        var subject=”Senior Prefect Application”;
        var message=”please fill in reference for +name”

        var waiver=driveapp.getfilebyID(“1T-LjVza7Rcx6Ucp61PssWmqmZQNzIMGdA6vpP4hcjvg”);
        var liabilitywaiver=waiver.getAs(mimeType.google_apps.document);

        mailapp Sendemail(refemail,subject,message[attachments[liabilitywaiver]});

  17. piyush says:

    hello,
    following error is poped up

    ReferenceError: “Mimetype” is not defined. (line 7, file “Code”)

    i want to send a pdf in my google drive,

    1. BrownBearWhatDoYouSee says:

      Make sure the code matches what I have in the example. I can see you are using “Mimetype” where it might need to be capitalized.

  18. Michael says:

    Thanks for the tutorial!
    What is necessary to send a .mobi ebook?

    I tried the code below but without success.

    var Ebook = DriveApp.getFileById(“0B2zkDomu7ddwLVEtUW4xZUpIU1k”);
    var EbookFile = Ebook.getAs(MimeType.MOBI);

    Thanks,
    Michael

    1. Michael says:

      I got it to send the file but only as a .bin file with the code below. Any thoughts on how to send the file and keep the extension the same?

      var Ebook = DriveApp.getFileById(“0B2zkDomu7ddwLVEtUW4xZUpIU1k”)
      var EbookFile = Ebook.getAs(“.mobi”)

      Thanks,
      Michael

      1. BrownBearWhatDoYouSee says:

        Hey Michael,

        That’s a great question. It doesn’t look like .mobi is a supported Mime Type as listed here in the Apps Script docs: https://developers.google.com/apps-script/reference/base/mime-type

        Have you tried just attaching the results of your call to getFileById? In other words, using the variable Ebook as the attachment instead of EbookFile? That might be something to try.

        The other workaround I could suggest would be to create a .zip file with the .mobi (and maybe a .pdf) inside and send that. The .zip file is a supported Mime Type, and most operating systems will automatically unzip a file for the user.

        Let me know how it goes.

        Thanks for reading, Jeff

  19. Amy says:

    Do you have to send the email from a gmail account or can you have the email send from a non-gmail account?

    1. BrownBearWhatDoYouSee says:

      I’ve had a couple of people ask this question, and every time I’ve pointed them to Gmail Aliases as a potential way: https://developers.google.com/apps-script/reference/gmail/gmail-app#getAliases()
      Not sure if it works or not since no one has ever reported back.

Leave a Reply

Your email address will not be published. Required fields are marked *