You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apps Script:HTML表单未输入收件人邮箱时点击发送需弹出MailApp UI提示

实现方案:前端校验+分情况弹窗提示

很简单,我们只需要在前端点击按钮时先做收件人邮箱的非空校验,再结合Google Script的回调函数来实现你的需求。这样既避免了无效的服务器调用,还能给用户精准的提示信息。

1. HTML 页面代码(比如命名为 index.html)

<!DOCTYPE html>
<html>
  <body>
    <div>
      <label for="recipient">目标收件人邮箱:</label>
      <input type="email" id="recipient" placeholder="请输入邮箱地址">
    </div>
    <button onclick="handleSendClick()">发送邮件</button>

    <script>
      // 处理发送按钮点击事件
      function handleSendClick() {
        const recipientInput = document.getElementById('recipient');
        const recipient = recipientInput.value.trim();

        // 第一步:前端校验收件人是否为空
        if (!recipient) {
          alert('请填写目标收件人邮箱!');
          recipientInput.focus(); // 让输入框获得焦点,方便用户输入
          return; // 终止后续操作,不调用服务器函数
        }

        // 校验通过,调用服务器端发送邮件函数
        google.script.run
          .withSuccessHandler(() => {
            eMailSent('邮件发送成功!🎉');
          })
          .withFailureHandler(error => {
            eMailSent(`邮件发送失败:${error.message} ❌`);
          })
          .sendEmail(recipient);
      }

      // 自定义弹窗函数,接收提示消息参数
      function eMailSent(message) {
        // 这里可以换成更美观的自定义弹窗,比如用Material Design组件
        alert(message);
      }
    </script>
  </body>
</html>

2. Google Apps Script 代码(Code.gs)

// 加载HTML页面
function doGet() {
  return HtmlService.createHtmlOutputFromFile('index')
    .setTitle('邮件发送工具');
}

// 服务器端发送邮件函数
function sendEmail(recipient) {
  // 额外加一层服务器端校验,防止前端校验被绕过
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!recipient || !emailRegex.test(recipient)) {
    throw new Error('收件人邮箱格式无效,请检查后重试');
  }

  // 执行邮件发送逻辑
  MailApp.sendEmail({
    to: recipient,
    subject: '测试邮件',
    body: '这是通过HTML Service发送的测试邮件'
    // 可以根据需求添加更多参数,比如cc、bcc、htmlBody等
  });
}

关键说明

  • 前端即时校验:在点击按钮后先判断输入是否为空,直接弹窗提示,不需要等待服务器响应,提升用户体验。
  • 分情况回调:利用google.script.run的withSuccessHandler和withFailureHandler,分别处理邮件发送成功和失败的情况,给用户不同的提示。
  • 服务器端二次校验:避免恶意用户绕过前端校验直接调用服务器函数,保证数据合法性。
  • 可扩展的弹窗:你可以把alert替换成更美观的自定义弹窗(比如结合Bootstrap或Material Design的模态框),提升UI质感。

内容的提问来源于stack exchange,提问作者Eric K.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:22:35