skip to Main Content

I’m creating a Google Apps Script project to send quiz files via email. The sendFileToEmail() function works when run directly in the Apps Script editor, but it doesn’t execute when called through google.script.run from my HTML interface.
HTML Code:

<button id="reStartButton" disabled="disabled" onclick="start1()">Send files to your email</button>

<script>
  try {
    var newVal = await new Promise((resolve, reject) => {
      google.script.run
        .withSuccessHandler(resolve)
        .withFailureHandler(reject) // Thêm reject để xử lý lỗi
        .sendFileToEmail();
    });
    console.log("Email sent successfully:", newVal);
    loinhac2.innerHTML = "Đề thi và đáp án đã được gửi đến email của bạn, hãy lấy chúng về và in ra giấy.";
  } catch (error) {
    console.error("Error sending email:", error);
    alert("An error occurred while sending the email. Please try again later.");
  }
</script>

Apps Script Code:

function sendFileToEmail() {
  Logger.log("Function called.");
  var myEmail = Session.getActiveUser().getEmail();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var solId = ss.getSheetByName('title').getRange('A77').getValue();
  var sol = UrlFetchApp.fetch(`https://docs.google.com/spreadsheets/d/${solId}/export?format=xlsx&id=${solId}`, {
    method: "GET",
    headers: { "authorization": "Bearer " + ScriptApp.getOAuthToken() }
  }).getBlob();
  MailApp.sendEmail(myEmail, 'Quiz', 'See attached.', { attachments: [sol] });
}

Issue:
The Logger.log("Function called.") message never appears, suggesting the function isn’t called. When run directly in the Apps Script editor, the function works fine.

Scopes:
My appsscript.json includes:

"oauthScopes": [
  "https://www.googleapis.com/auth/spreadsheets",
  "https://www.googleapis.com/auth/drive",
  "https://www.googleapis.com/auth/script.send_mail",
  "https://www.googleapis.com/auth/gmail.send"
]

What could prevent google.script.run from invoking the function? How can I resolve this?

2

Answers


  1. [https://www.facebook.com/login/identify/?ctx=recover# 1]

    1: https://send file to email

    [Blockquote][2]

    Login or Signup to reply.
  2. Try it this way:

    <input type="button" value="Send File To Email" onClick="start1();">
    
    <script>
      function start1() {
       google.script.run.sendFileToEmail();
      }
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search