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

Ahm*_*san 2 javascript google-api node.js gmail-api

我正在使用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
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

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

enter code here我可以在哪里从本地找到附加文件的partId和零件数组

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

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

Ahm*_*san 5

经过一番研究,我找到了一个使用 Gmail API 创建草稿时附加图像的解决方案,我从这个源中得到了提示发送带有附件的邮件

这是完整的工作示例:

步骤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;
}
Run Code Online (Sandbox Code Playgroud)

第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
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

也可以使用这个npm包mimemessage