如何在 Node.JS 中使用 gmail API 创建带附件的草稿邮件?

How to create draft message with attachment using gmail API in Node.JS?

我正在使用 Gmail API 的,需要创建带有附件的新草稿,我正在按照官方文档进行操作:https://developers.google.com/gmail/api/v1/reference/users/drafts/create


    let response2 = await gmail.users.drafts.create({
        'userId': 'me',
        'resource': {
            'message': {
                'raw': payload
            }
        }
    });

此代码段在 Gmail 中创建邮件草稿,但无法从我的本地计算机附加文件

我在哪里可以找到来自本地

enter code here附加文件的 partId 和 Parts Array

有效负载参考:https://www.any-api.com/googleapis_com/gmail/docs/Definitions/MessagePart

// -- -- payload for post request -- -- //
// ------------------------------------ //
{
  "body": {
    "attachmentId": "",
    "data": "",
    "size": 0
  },
  "filename": "",
  "headers": [
    {
      "name": "",
      "value": ""
    }
  ],
  "mimeType": "",
  "partId": "",
  "parts": [
    {
      "body": {},
      "filename": "",
      "headers": [
        null
      ],
      "mimeType": "",
      "partId": "",
      "parts": [
        null
      ]
    }
  ]
}

经过一些研究,我找到了一个在使用 Gmail 创建草稿时附加图像的解决方案 API,我从这个来源得到了提示 Sending mail with attachment

这是完整的工作示例:

第 1 步:

function makeBody(subject, message, receiverId) {
    var boundary = "__myapp__";
    var nl = "\n";
    var attach = new Buffer(fs.readFileSync(__dirname + "/../" + fileName)).toString("base64");
    // console.dir(attach);
    var str = [

        "MIME-Version: 1.0",
        "Content-Transfer-Encoding: 7bit",
        "to: " + receiverId,
        "subject: " + subject,
        "Content-Type: multipart/alternate; boundary=" + boundary + nl,
        "--" + boundary,
        "Content-Type: text/plain; charset=UTF-8",
        "Content-Transfer-Encoding: 7bit" + nl,
        message + nl,
        "--" + boundary,
        "--" + boundary,
        "Content-Type: Application/pdf; name=myPdf.pdf",
        'Content-Disposition: attachment; filename=myPdf.pdf',
        "Content-Transfer-Encoding: base64" + nl,
        attach,
        "--" + boundary + "--"

    ].join("\n");

    var encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
    return encodedMail;
}

第 2 步:


const auth = await authorize(accessToken);
const gmail = google.gmail({
    version: 'v1',
    auth
});
var rawText = makeBody("This is subject", "This is message", "test@gmail.com");
var res = await gmail.users.drafts.create({
    'userId': 'me',
    'resource': {
        'message': {
            'raw': rawText
        }
    }
});

也可以使用这个npm包mimemessage