I have a javacript that create an Html file and i wanna send it to some email addresses
So i made an app script doPost seen below...
But everytime try to send the emails with my button on my web page i've got that error.
Access to fetch at 'https://script.google.com/macros/s/AKfycbxHm00gB_Uiv7lK78dDW68cBeFkXz_84G4Q4eJcBIV2gZ1Yowo1cqTgeAr-9kG_rOEB/exec' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
i'm stuck
function doPost(e) {
let finalOutput = {};
const headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS", // Specify allowed methods
"Access-Control-Allow-Headers": "*" // Specify allowed headers
};
try {
// 1. Récupération des deux paramètres principaux
const rapportHTML = e.parameters.htmlContent;
const destinataires = e.parameters.destinatairesContainer;
console.log( "Rapport Html : " + rapportHTML + "\n" + "Destinataires :" + destinataires );
// Récupération des données pour le sujet
const ligue = e.parameters.ligue || 'Not specified';
const categorie = e.parameters.categorie || 'Not Specified';
const matchDomicile = e.parameters.match_domicile || 'Unknown';
const matchVisiteur = e.parameters.match_visiteur || 'Unknown';
// 🛑 ADRESSE D'EXPÉDITION (Alias) (Optionnel - Si nécessaire pour GmailApp)
const aliasExpediteur = ''; // Ex: '[email protected]'
if (!rapportHTML || !destinataires) {
throw new Error("Contenu du rapport (htmlContent) ou Destinataires (destinatairesContainer) manquants.");
}
// 2. Construction du sujet
const subject = `Rapport d'Expulsion: ${matchDomicile} vs ${matchVisiteur} (${ligue} / ${categorie})`;
// 3. Configuration de l'e-mail
const emailOptions = {
to: destinataires,
subject: subject,
htmlBody: rapportHTML
};
if (aliasExpediteur) {
emailOptions.from = aliasExpediteur;
}
// 4. Envoi de l'e-mail avec GMAILAPP
GmailApp.sendEmail(emailOptions);
// 5. Réponse SUCCESS
finalOutput = {
success: true,
message: `E-Mail sent to : ${destinataires}`
};
} catch (error) {
// 6. Réponse ERREUR
finalOutput = {
success: false,
error: "Error sending Email: " + error.message,
};
}
// 7. FIX CORS (LIGNE CORRIGÉE ET SÉPARÉE)
return ContentService.createTextOutput(JSON.stringify(finalOutput))
.setMimeType(ContentService.MimeType.JSON)
.addCORSHeaders(headers); // Add CORS headers to error responses as well
return finalOutput;
}
function addCORSHeaders(response, headers) {
for (const header in headers) {
response.addHeader(header, headers[header]);
}
return response;
}
i tried to put setAccessControlAllowOrigin('*'); Didn't work;
i'm kinda new to that.
1 Answer 1
You are encountering this error because Google Apps Script web applications do not include CORS headers by default.
Browsers always send an OPTIONS request before a POST during cross-origin requests. It's essential to implement a function to handle this separatly.
const doOptions = (e) => {
return ContentService.createTextOutput('')
.setMimeType(ContentService.MimeType.JSON)
.setHeader('Access-Control-Allow-Origin', '*')
.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS')
.setHeader('Access-Control-Allow-Headers', '*');
}
The function is triggered whenever an OPTIONS request is received by the web app, and it sends back the necessary CORS headers to permit the subsequent POST request.
The method .addCORSHeaders you attempted to use is not effective for HTTP headers in Apps Script. Instead, utilise .setHeader as described above for better results.
4 Comments
doOptions() function get called? Note the the word doOptions doesn't appear in any of Google's official Apps Script documentation. This answer seems to be a hallucination.doGet() and doPost(). What makes you think your doOptions() function ever gets called? Use console.log() to confirm that it actually runs, then edit the answer to describe how the function gets called.Explore related questions
See similar questions with these tags.