按步骤调用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 ofTo:—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

