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

huangapple go评论90阅读模式
英文:

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

以下是代码片段,用于在Gmail中创建草稿消息,但无法附加来自我的本地计算机的文件。

在哪里可以找到partIdParts Array来附加本地文件?

payload参考:https://www.any-api.com/googleapis_com/gmail/docs/Definitions/MessagePart

// -- -- post请求的payload -- -- //
// ------------------------------------ //
{
  "body": {
    "attachmentId": "",
    "data": "",
    "size": 0
  },
  "filename": "",
  "headers": [
    {
      "name": "",
      "value": ""
    }
  ],
  "mimeType": "",
  "partId": "",
  "parts": [
    {
      "body": {},
      "filename": "",
      "headers": [
        null
      ],
      "mimeType": "",
      "partId": "",
      "parts": [
        null
      ]
    }
  ]
}
英文:

I'm working with Gmail API's, Need to create the new draft with the attachment, I am following the official documentation: https://developers.google.com/gmail/api/v1/reference/users/drafts/create


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

this snippet creates the draft message in Gmail, but unable to attach the file from my local machine

Where I can found the partId and Parts Array to the enter code hereattached file from local

payload Refrence: https://www.any-api.com/googleapis_com/gmail/docs/Definitions/MessagePart

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

<!-- end snippet -->

答案1

得分: 5

以下是翻译好的内容:

Step 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;
}

Step 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

英文:

After some research, I found a solution to attach an image while create a draft using Gmail API, I got the hint from this source Sending mail with attachment

This is the complete working example:

Step 1:

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

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

    ].join(&quot;\n&quot;);

    var encodedMail = new Buffer(str).toString(&quot;base64&quot;).replace(/\+/g, &#39;-&#39;).replace(/\//g, &#39;_&#39;);
    return encodedMail;
}

Step 2:


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

Also can use this npm package mimemessage

huangapple
  • 本文由 发表于 2020年1月6日 21:42:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613195.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定