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

按步骤调用Gmail API时出现400错误:Recipient address required

Hey there! That 400 error with "Recipient address required" is super common when working with the Gmail API's send endpoint—let's break down what's going wrong and fix it step by step.

Why this error happens

This error means your API request is missing required recipient information. The Gmail API's users.messages.send endpoint mandates that you specify at least one recipient in either the To, Cc, or Bcc field of your email's MIME content. Most often, this happens because the raw email content you're sending doesn't include a valid recipient header.

Fixes to try

1. Ensure your MIME email content includes a recipient header

The raw email string you encode must follow standard MIME format, which requires a To: (or Cc/Bcc) field. Here's a correct example of building that content:

function buildEmailContent(to, subject, body) {
  // Encode subject and body to handle special characters
  const encodedSubject = encodeURIComponent(subject).replace(/%20/g, '+');
  const encodedBody = encodeURIComponent(body).replace(/%20/g, '+');
  
  // Critical: Include the To field here!
  return `To: ${to}\r\nSubject: ${encodedSubject}\r\n\r\n${encodedBody}`;
}

2. Use URL-safe Base64 encoding for the raw content

Gmail API requires URL-safe Base64 encoding (replace + with -, / with _, and strip trailing =). Here's how to combine this with the API call:

function sendTestEmail() {
  const recipient = 'your-recipient@example.com';
  const emailSubject = 'Test via Gmail API';
  const emailBody = 'Hello, this is a test message!';

  // Build valid MIME content
  const rawEmail = buildEmailContent(recipient, emailSubject, emailBody);
  
  // Convert to URL-safe Base64
  const encodedEmail = btoa(rawEmail)
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/, '');

  // Call the Gmail API (assuming you've already handled OAuth auth)
  gapi.client.gmail.users.messages.send({
    userId: 'me',
    resource: {
      raw: encodedEmail
    }
  })
  .then(response => console.log('Email sent:', response))
  .catch(err => console.error('Failed to send:', err));
}

3. Double-check for common typos

  • Make sure you didn't misspell the header (e.g., to: instead of To:—while MIME is case-insensitive, sticking to standard capitalization avoids edge cases).
  • Verify the recipient email address is valid (no missing @, typos in the domain, etc.).

Quick troubleshooting tip

Before encoding the raw email content, log it to your console to confirm the To: field is present and correctly formatted. If that part looks good, double-check your Base64 encoding—invalid encoding can cause the API to fail parsing the email, leading to this misleading error.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:49:18