Javascript调用Gmail API时遇‘Missing draft message’错误求助
解决Gmail API "Missing draft message" 错误
你的代码里存在几个关键问题,导致请求失败并返回该错误,下面逐一修正:
错误点1:URL格式错误
请求URL里多余了HTTP/1.1,这是HTTP协议标识,不属于URL的一部分,必须移除。
错误点2:请求头配置错误
ContentType的键名拼写错误,正确的是Content-Type(带连字符)- 请求头参数必须放在
headers对象内部,不能和method同级
错误点3:请求体未正确传递
Gmail API的创建草稿接口要求请求体是JSON格式的字符串,你需要把message对象用JSON.stringify转换后,放在body字段中,而不是直接作为options的属性。
错误点4:Raw字段编码不符合要求
Gmail的raw字段需要的是URL安全的Base64编码,且邮件内容必须符合RFC 2822格式(包含必要的邮件头,比如Subject、From等),单纯用btoa编码普通字符串是不满足要求的。
修正后的完整代码
// 构造符合RFC 2822格式的邮件内容 const emailContent = `Subject: My Draft\r\n\r\nThis is the body of my draft email.`; // 转换为URL安全的Base64编码 function base64UrlEncode(str) { return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (match, p1) => { return String.fromCharCode(`0x${p1}`); })) .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=+$/, ''); } const msgBody = base64UrlEncode(emailContent); const token = localStorage.getItem("accessToken"); fetch( "https://gmail.googleapis.com/gmail/v1/users/me/drafts?key=[my api key]", { method: "POST", headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json", "Accept": "application/json" }, body: JSON.stringify({ message: { raw: msgBody } }) } ) .then((data) => data.json()) .then((response) => console.log(response)) .catch((error) => console.error('Error:', error));
额外说明
- 确保你的accessToken拥有
https://www.googleapis.com/auth/gmail.compose权限,这是创建草稿必需的权限范围 - 邮件内容必须包含正确的邮件头(比如
Subject),否则即使API请求成功,草稿也可能显示异常
内容的提问来源于stack exchange,提问作者Muzammil Zafar
相关产品推荐
相关产品推荐

