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

在Google Apps Script中加载AWS SDK报错:AWS未定义

解决Google Apps Script中AWS未定义的问题

问题原因

AWS JavaScript SDK的浏览器版本会将AWS对象挂载到浏览器的window全局对象上,但Google Apps Script(GAS)的运行环境中没有window对象,直接通过eval加载SDK后,AWS无法被识别为全局对象,因此报错"AWS is not defined"。

解决方案

方法一:手动绑定SDK到GAS全局对象

修改SDK加载代码,将脚本中的window替换为GAS的全局对象globalThis,让SDK能正确挂载AWS:

function sendemail(email,name,code,date,expiry,version) {
  // 加载AWS SDK并绑定到GAS全局对象
  const sdkCode = UrlFetchApp.fetch("https://sdk.amazonaws.com/js/aws-sdk-2.1206.0.min.js").getContentText();
  eval(`(function(window){${sdkCode}})(globalThis)`);

  const configure = {
      accessKeyId: PropertiesService.getScriptProperties().getProperty('ACCESS_KEY_ID'),
      secretAccessKey: PropertiesService.getScriptProperties().getProperty('SECRET_ACCESS_KEY'),
      apiVersion: '2010-12-01',
      region: 'us-east-1'
  };
  
  const ses = new AWS.SES(configure);

  // 后续发送邮件的逻辑...
}

关键注意事项

  • 不要硬编码密钥:将AWS密钥存储在GAS的「脚本属性」中(脚本编辑器 → 设置 → 脚本属性),通过PropertiesService读取,避免密钥泄露。
  • 验证发件邮箱:在AWS SES控制台中验证用于发送邮件的邮箱或域名,否则邮件会被拒绝。
  • 权限配置:确保GAS项目拥有访问外部URL(AWS SDK地址)和读取脚本属性的权限,首次运行时会提示授权。

完整示例(含邮件发送逻辑)

function sendemail(email,name,code,date,expiry,version) {
  const sdkCode = UrlFetchApp.fetch("https://sdk.amazonaws.com/js/aws-sdk-2.1206.0.min.js").getContentText();
  eval(`(function(window){${sdkCode}})(globalThis)`);

  const configure = {
      accessKeyId: PropertiesService.getScriptProperties().getProperty('ACCESS_KEY_ID'),
      secretAccessKey: PropertiesService.getScriptProperties().getProperty('SECRET_ACCESS_KEY'),
      apiVersion: '2010-12-01',
      region: 'us-east-1'
  };
  
  const ses = new AWS.SES(configure);

  // 构建邮件参数
  const emailParams = {
    Destination: { ToAddresses: [email] },
    Message: {
      Body: {
        Html: {
          Charset: "UTF-8",
          Data: `<p>您好 ${name},您的验证码是 <strong>${code}</strong>,有效期至 ${expiry}</p>`
        },
        Text: {
          Charset: "UTF-8",
          Data: `您好 ${name},您的验证码是 ${code},有效期至 ${expiry}`
        }
      },
      Subject: {
        Charset: "UTF-8",
        Data: "您的验证码邮件"
      }
    },
    Source: "your-verified-email@example.com" // 替换为SES已验证的发件邮箱
  };

  // 发送邮件
  ses.sendEmail(emailParams, (err, data) => {
    if (err) {
      console.error("发送失败:", err);
    } else {
      console.log("发送成功:", data.MessageId);
    }
  });
}

内容的提问来源于stack exchange,提问作者kartik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:45:58