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

使用Gmail API发送邮件时如何获取RFC822 Message-Id?

How to Retrieve the RFC822 Message-Id After Sending Emails via Gmail API (Node.js)

Great question! The RFC822 Message-Id does exist for every email sent through the Gmail API—you just won’t get it in the immediate response from the users.messages.send endpoint. That initial response only gives you Gmail’s internal id (a unique identifier for the message within Gmail’s system), not the standard Message-Id defined in RFC822.

Here’s how to fetch it using the Node.js Gmail client library:

Step-by-Step Solution

  1. Send the email as usual and capture the Gmail internal id from the response.
  2. Fetch the message’s headers using the users.messages.get endpoint, specifically requesting the Message-Id header to keep things efficient.

Example Code

const { google } = require('googleapis');

async function sendEmailAndGetMessageId(auth) {
  const gmail = google.gmail({ version: 'v1', auth });

  // 1. Send your email (replace with your existing send logic)
  const sendResult = await gmail.users.messages.send({
    userId: 'me',
    requestBody: {
      raw: 'your_base64_url_encoded_email_content' // Ensure your email is properly encoded
    }
  });

  const gmailInternalId = sendResult.data.id;

  // 2. Fetch only the Message-Id header from the sent message
  const messageDetails = await gmail.users.messages.get({
    userId: 'me',
    id: gmailInternalId,
    format: 'metadata',
    metadataHeaders: ['Message-Id'] // Target only the header we need
  });

  // Extract the RFC822 Message-Id from the headers
  const messageIdEntry = messageDetails.data.payload.headers.find(
    header => header.name === 'Message-Id'
  );
  const rfc822MessageId = messageIdEntry ? messageIdEntry.value : null;

  console.log('RFC822 Message-Id:', rfc822MessageId);
  return rfc822MessageId;
}

Bonus: Customize Your Message-Id

If you want to set your own Message-Id instead of letting Gmail generate one, you can include it directly in your raw email content before encoding. Just add the header in your RFC822-formatted email:

Message-Id: <my-custom-unique-id@my-domain.com>
From: "Your Name" <you@example.com>
To: "Recipient" <recipient@example.com>
Subject: Test Email
... rest of your email content ...

Gmail will respect this custom Message-Id as long as it follows RFC822 formatting rules (enclosed in angle brackets, unique across all emails).

Why This Works

The users.messages.get endpoint with format: 'metadata' lets you fetch only specific headers instead of the entire email, which is faster and uses less bandwidth. The Message-Id is always present in the email’s headers, whether generated by Gmail or set by you.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:08:00