Search code examples
formsemailgoogle-apps-scriptgoogle-forms

Is there any workaround to specify sender's email address for automatic email sending upon form submission?


I have a script which is working for automatic email sending upon form submission.

User submit form > Email send out to specified email address from my own email that I used to setup the script.

Is there any workaround to have the email sender to specify to be the form submitter?

I look at the MailApp class specification. The best I could find is specifying a noreply as 'true'. https://developers.google.com/apps-script/reference/mail/mail-app#sendEmail(String,String,String,Object)

I want to tweak for my script to play a role as invisible middle man to send the email on form submitter's behalf, and also to discourage replies to the email that I used to setup the script.

Thanks


Solution

  • I found a workaround to send with another group alias email. Instead of using MailApp class, I combine the usage of GmailApp class.

    Prerequisite: adding group alias email as 'Send as' in your Gmail. How-to here

    After adding the send as alias, use GmailApp.sendEmail with the option to indicate from. Step:

    I'm skipping the steps of form submitting, triggers and retrieving values as this question is not about how-to do those. The steps below assumed all the steps done until retrieved email body to prepare for the email sending

    1. add group alias email as 'Send as' in your Gmail (see prerequisite above).
    2. test whether you can send an email in a particular group account email. (huge credit to this post). Code:

        var aliases = GmailApp.getAliases();
        var num = aliases.length-1;
        if (num<0){
            return false
          }else{
            for (var i = 0;i <= num;i++){
              if (aliases[i] == "[email protected]"){
                var myGroupMail=aliases[i];
                break;
              }
            }
          }
          if (myGroupMail != "[email protected]"){return false}

    1. retrieve email html body if you want to send in html. For example, you can retrieve a template from a google doc with DocumentApp.openByUrl and getId() and convert doc to HTML via code:

    function docToHtml(docId) {
    
      // Downloads a Google Doc as an HTML string.
      var url = "{{insert your doc url}}" +
                docId + "&exportFormat=html";
      var param = {
        method: "get",
        headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
        muteHttpExceptions: true,
      };
      return UrlFetchApp.fetch(url, param).getContentText();
    }

    1. Finally send your email :)

    sendEmail(recipient, EMAIL_SUBJECT, '', {
        cc: email,
        htmlBody: {{insert your create Email Body Function or use the doctohtml code above}},
        from: myGroupMail
      }