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

如何用Gmail API在JavaScript中更新邮件正文?400错误求助

Gmail API 更新邮件正文 400 错误修复方案

问题根源

你的代码存在几个关键错误,导致了400请求失败:

  • 接口路径错误:/modify接口仅用于修改邮件标签、星标等属性,无法更新邮件正文,需使用users.messages.update接口。
  • API_KEY 拼接错误:URL 中key=['API_KEY']是硬编码字符串,未替换为实际变量,应改为${API_KEY}。
  • Raw 参数格式错误:Gmail API 的raw要求完整的 RFC 2822 格式邮件(包含发件人、收件人、主题等邮件头+正文),而非仅对正文做Base64编码。
  • 错误处理缺失:catch块为空,无法排查具体错误原因。

修正后的代码

var token = localStorage.getItem("accessToken");
var messageId = "18514426e2b99017";

async function updateMessageBody() {
  // 构建完整的MIME格式邮件内容
  const updatedEmail = `From: "John" <your-email@gmail.com>
To: "Recipient" <recipient-email@example.com>
Subject: 邮件主题(保持原主题或修改)
Content-Type: text/plain; charset="UTF-8"

Hello,

This is the UPDATED message body.

Best regards,
John`;

  const API_KEY = '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-CXIk';
  const headers = {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  };

  // 生成URL安全的Base64编码
  const raw = window.btoa(unescape(encodeURIComponent(updatedEmail)))
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/, '');

  const response = await fetch(`https://gmail.googleapis.com/gmail/v1/users/me/messages/${messageId}?key=${API_KEY}`, {
    method: 'PUT', // update接口使用PUT方法
    headers: headers,
    body: JSON.stringify({
      raw: raw
    })
  });

  if (!response.ok) {
    const errorDetails = await response.json();
    throw new Error(`请求失败: ${response.status} - ${JSON.stringify(errorDetails)}`);
  }

  return await response.json();
}

updateMessageBody()
  .then(response => {
    console.log('邮件正文更新成功:', response);
  })
  .catch(error => {
    console.error('更新失败:', error.message);
  });

额外注意事项

  • 替换代码中的your-email@gmail.com和recipient-email@example.com为实际邮箱地址,主题可根据原邮件调整。
  • 授权时需确保包含https://www.googleapis.com/auth/gmail.modify或更高权限(如gmail.compose)。
  • 必须使用URL安全的Base64编码,避免特殊字符导致请求解析失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 02:20:46