Warm tip: This article is reproduced from serverfault.com, please click

其他-使用 microsoft graph rest api 从邮件中下载附件

(其他 - download attachments from mail using microsoft graph rest api)

发布于 2019-02-22 05:52:25

我已经使用 microsoft graph rest api 成功获取了收件箱中的邮件列表,但我很难理解有关如何从邮件下载附件的文档。

在此处输入图片说明

例如:this question stackoverflow answer谈到了我打算实现的目标,但我不明白提到的端点中的 message_id 是什么:https://outlook.office.com/api/v2.0/me/messages/{message_id}/attachments

更新

我能够使用以下端点获取附件的详细信息:https : //graph.microsoft.com/v1.0/me/messages/ {id}/attachments并得到以下响应。

在此处输入图片说明

我的印象是响应可能包含下载附件的链接,但是响应包含名为 contentBytes 的密钥,我猜它是文件的加密内容。

Questioner
Irfan Harun
Viewed
0
Vadim Gremyachev 2019-02-26 21:01:53

对于attachment资源文件类型 contentBytes属性返回

文件的 base64 编码内容

例子

以下 Node.js 示例演示了如何获取附件属性和附件内容(依赖于requestlibrary):

const attachment = await getAttachment(
    userId,
    mesasageId,
    attachmentId,
    accessToken
);
const fileContent = new Buffer(attachment.contentBytes, 'base64');
//...

在哪里

const requestAsync = options => {
  return new Promise((resolve, reject) => {
    request(options, (error, res, body) => {
      if (!error && res.statusCode == 200) {
        resolve(body);
      } else {
        reject(error);
      }
    });
  });
};

const getAttachment = (userId, messageId, attachmentId, accessToken) => {
  return requestAsync({
    url: `https://graph.microsoft.com/v1.0/users/${userId}/messages/${messageId}/attachments/${attachmentId}`,
    method: "GET",
    headers: {
      Authorization: `Bearer ${accessToken}`,
      Accept: "application/json;odata.metadata=none"
    }
  }).then(data => {
    return JSON.parse(data);
  });
};

更新

以下示例演示如何在浏览器中将附件下载为文件

try {
  const attachment = await getAttachment(
    userId,
    mesasageId,
    attachmentId,
    accessToken
  );

  download("data:application/pdf;base64," +  attachment.contentBytes, "Sample.pdf","application/pdf");
} catch (ex) {
  console.log(ex);
}

在哪里

async function getAttachment(userId, messageId, attachmentId, accessToken){
    const res = await fetch(
      `https://graph.microsoft.com/v1.0/users/${userId}/messages/${messageId}/attachments/${attachmentId}`,
      {
        method: "GET",
        headers: {
          Authorization: `Bearer ${accessToken}`,
          Accept: "application/json;odata.metadata=none"
        }
      }
    );
    return res.json();
 }

依赖:download.js