Having Trouble with Sending Emails Using Google Scripts - Javascript POST Request Issue

I have been working on setting up a basic form on my website where users can input their name, email, and a short message. This information is then sent to Google Apps Script which forwards the message to me via email. Unfortunately, I keep encountering an issue with the Google Apps Script showing a status of failed. I attempted using Logger.log() for debugging purposes, but no logs are visible in the cloud log when I try to check. Below is the JavaScript code snippet for the front end:

      const url = "https://script.google.com/macros/s/AKfycbyedfmVexnnu9oTATVADIbe5oYQbrDpmNWGLcrtSpKtFBZWA9RgnugohF9mLCHeGJc4/exec"
        const data = {
            name: $emailName.val(),
            email: $emailEmail.val(),
            message: $emailMessage.val()
        }
        // const payload = JSON.stringify(data)
        const options = {
            method: 'POST',
            mode: "no-cors",
            contentType: 'application/json',
            payload: JSON.stringify(data)
        }
        console.log(options)
        fetch(url, options)
        .then((response) => {
            console.log("success", response);
        }).catch((error) => {
            console.log(error)
        })
        
    })

})
.catch((error) => {
    console.log(error);
})

Below is the Google Script that I have implemented:

function doPost(e) {

Logger.log(e);

var reply = JSON.parse(e.parameters.email);
var name = JSON.parse(e.parameters.name);
var message = JSON.parse(e.parameters.message);

newMessage = "You have a new email from " + name + ", and you can reply back to them at email " + reply + ". Message below. \n\n\n\n" + message;

object = {
  to: "************",
  replyTo: reply,
  subject: "New Message from " + name,
  body: newMessage
};

  MailApp.sendEmail(object);

return ContentService.createTextOutput(JSON.stringify(e.parameter));


}

If anyone could assist in diagnosing this problem effectively, it would be greatly appreciated as I have spent hours troubleshooting without success. Thank you!

SOLUTION

Front End:

       const url = "https://script.google.com/macros/s/******/exec"
        const data = {
            name: $emailName.val(),
            email: $emailEmail.val(),
            message: $emailMessage.val()
          }
          const options = {
            method: 'POST',
            body: JSON.stringify(data),
          }
          console.log(options)
          fetch(url, options)
          .then((response) => response.text())
          .then((response) => console.log(response))
          .catch((error) => console.log(error))
        
    })

GOOGLE SCRIPT:

function doPost(e) {
  var {name, email, message} = JSON.parse(e.postData.contents);
  var reply = email;
  newMessage = "You have a new email from " + name + ", and you can reply back to them at email " + reply + ". Message below. \n\n\n\n" + message;
  object = {
    to: "*****",
    replyTo: reply,
    subject: "New Message from " + name,
    body: newMessage
  };
  MailApp.sendEmail(object);
  return ContentService.createTextOutput(object);
}

Don't forget to refresh your browser after making changes. It solved my problem after struggling for hours. Huge thanks to Tanaike for the guidance!

Answer №1

Changes to Implement:

  • For your JavaScript code:
    • When using the fetch function, make sure to set the data to body instead of payload.
    • There is no property called contentType in this context.
    • The use of mode: "no-cors" is not necessary for this case.
  • Regarding your Google Apps Script:
    • In this scenario, retrieve the value from body using e.postData.contents.

Once you incorporate the above modifications into your script, it should look like the following:

Updated script:

JavaScript Code:

const url = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9eeaffe7f2f1ecf6ebf9f6fbedaca7afdef9f3fff7f2b0fdf1f3">[email protected]</a>"
const data = {
  name: $emailName.val(),
  email: $emailEmail.val(),
  message: $emailMessage.val()
}
const options = {
  method: 'POST',
  body: JSON.stringify(data),
}
console.log(options)
fetch(url, options)
.then((response) => response.text())
.then((response) => console.log(response))
.catch((error) => console.log(error))

Google Apps Script:

function doPost(e) {
  var {name, email, message} = JSON.parse(e.postData.contents);
  var reply = email;
  newMessage = "You have a new email from " + name + ", and you can reply back to them at email " + reply + ". Message below. \n\n\n\n" + message;
  object = {
    to: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9eeaffe7f2f1ecf6ebf9f6fbedaca7afdef9f3fff7f2b0fdf1f3">[email protected]</a>",
    replyTo: reply,
    subject: "New Message from " + name,
    body: newMessage
  };
  MailApp.sendEmail(object);
  return ContentService.createTextOutput(JSON.stringify(e));
}

Note:

  • If you made changes to the Google Apps Script for Web Apps, remember to update the deployment as a new version. This ensures that the modifications are applied to the Web Apps. Please proceed with caution when doing this.
  • For more information, refer to the guide on "Redeploying Web Apps without Changing URL of Web Apps for new IDE".

References:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ModSecurity Action Causing AJAX Problem

An error is being triggered by the URL below with a message of "Modsecurity forbidden status code: 403". This URL is being returned from an AJAX call. like ? and active = ?&params='%ABCDE%'|1&element_id=hello If I remove %% from ABCDE ...

Turn off all animations for a specific div or HTML page

Whenever I add an item to a div, there's this strange flashing animation happening. It's like a blink or flash that updates the div with new data. I'm not entirely sure if it's a jQuery animation or not. Is there any way to disable all ...

Fastify route handler failing to start after onRequest hook is executed

I am currently working on a fastify application that needs to capture the raw body of post requests for authentication purposes. After extensive research, I discovered that fastify does not have native support for this feature. The solutions I found online ...

Adding a JavaScript variable into a Django template tag

This particular situation has been presenting a challenge for me. So far, I have been using query parameters instead of a variable within the {% url %} tag. However, I can't help but wonder if there is a way to achieve this: I am interested in includ ...

Utilizing a backup system to store environment variables within a configuration file

Currently, I am utilizing my environment variables by directly referencing process.env.NODE_ENV throughout my application. While this method works, it is becoming challenging to manage and keep track of. Therefore, I would like to consolidate all these var ...

`Need help setting the active class for a bootstrap navbar using Angular JS?`

In my bootstrap navbar, I have the following menu items: Home | About | Contact I'm looking to assign the active class to each menu item based on the current angular route. Specifically, how can I set class="active" when the angular route is at # ...

What are the steps to designing a unique JSON data format?

When working with a JSON data structure containing 100 objects, the output will resemble the following: [{ "Value": "Sens1_001", "Parent": Null, "Child": { "Value": "Sens2_068", "Parent":"Sens1_001", "Child" : { ...

Generating intricate JSON data structures with a combination of WCF LINQ-to-SQL and REST in C# ASP.NET

Within my web application, there is a login page where users can log in. Once logged in, I need to retrieve the Account object, which contains an EntitySet of Player: public Account Login(string email, string password) { var query = (from p in db.Acco ...

Utilizing Filter in ReactJS to Avoid Displaying Duplicate Entries in an Array

I am facing an issue on my ReactJS page where two dropdown lists are showing duplicate values. These values are retrieved from a json file. I have tried using the filter method to eliminate duplicates, but I am unsure about how to apply it in my array whil ...

FirebaseError encountered: Unable to update document due to absence of document. Updating document is only possible if document id is hard coded

For my latest project, I have a component that can successfully create a new user and add them to the database using the function createUserWithEmailAndPassword(auth, email, password). Now, I am working on another component that will allow users to edit t ...

Utilize Jquery to locate and update the text of all div elements that have an empty id attribute

I need help with a task involving a list of divs, some with ids and some without. My goal is to identify all the divs within a specific class that have empty ids and change their inner text to say "no data available". Can this be done? My attempt using $( ...

Issues with the functionality of jQuery's .load() method are causing

I am encountering an issue for the first time. Inside ajax.html, I have the following code in the header: $(document).ready(function(){ $( "#result" ).load( "/loaded.html" ); }); In the same directory, there is a second page named loaded.html: <d ...

What is the best way to execute tests in different environments with Protractor?

Is it possible to execute specifications in various environments? Maybe by adjusting the protractor-config file? Could we do something along the lines of specs: ['../tests/*.js', server1], ['../more_tests/*.js', server2] within the ...

The "Open in new tab" feature seems to be missing for links when using Safari on iOS

My webapp contains links structured like this: <a href="/articles/">Articles</a> I am using JavaScript to control these links within my app: $(document).on("click", 'a', function(ev) { ev.preventDefault(); ev.stopPropagat ...

Update a separate React component in response to the interaction with a different React component

Currently, I am working with a react component named Interest Category that showcases an initial set of Interest categories. Another react component called CreateInterestCategoryDialog, which functions as a modal, is responsible for creating a new entity I ...

Is it possible to share a MySQL connection for cross-module usage in Node/Express by utilizing promise-mysql?

Currently, I am trying to import and utilize a database module within one of my controllers. Despite successfully establishing the initial connection, I am encountering an error when accessing any of my routes through the browser: "Cannot read property ...

I am having difficulty with my JavaScript code not being able to interpret the JSON output from my PHP code. Can anyone help me troubleshoot

Having trouble working with an AJAX call and handling the JSON object it generates in JavaScript? Here's a sample snippet of PHP code returning the JSON object: echo json_encode(array("results" => array(array("user" => $member['user'] ...

When the jQuery document is ready, it typically returns null, but the console can still access and display

I have encountered an issue while working on a solution within a CMS (EPiServer). When I utilize console.log to check my object, it displays a null value. $(document).ready(function () { console.log("$('.EPiRequester').html() =" + $('. ...

Utilizing JQuery to make Google listings easily findable

Implementing Google Places for a location text box has been successful. However, I am now looking to create a class-based implementation so that I can use it with multiple places effortlessly. Is it possible to achieve this using JQuery? <script type ...

Developing a Typescript module, the dependent module is searching for an import within the local directory but encounters an issue - the module cannot be found and

After creating and publishing a Typescript package, I encountered an issue where the dependent module was not being imported from the expected location. Instead of searching in node_modules, it was looking in the current folder and failing to locate the mo ...