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!