使用Microsoft Graph Rest API从邮件下载附件

时间:2019-02-22 05:52:25

标签: microsoft-graph microsoft-graph-mail

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

enter image description here

例如:这个问题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获取附件的详细信息,并得到以下响应。

enter image description here

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

2 个答案:

答案 0 :(得分:0)

对于attachment resource contentBytes属性的file type,返回

  

以base64编码的文件内容

示例

下面的Node.js示例演示了如何获取附件属性以及附件内容(与request library有依赖性):

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 library

答案 1 :(得分:0)

我不知道这是否有帮助,但您只需在请求的末尾添加 /$value :

https://graph.microsoft.com/v1.0/me/messages/{message_id}/attachments/{attachment_id}/$value