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

标签 microsoft-graph-api 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 的 key ,我猜这是文件的加密内容。

最佳答案

对于attachment resourcefile type contentBytes 属性返回

base64-encoded contents of the file

示例

以下 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();
 }

Dependency: download.js library

关于microsoft-graph-api - 使用 microsoft graph rest api 从邮件下载附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54820844/

相关文章:

office365 - 订阅验证请求失败。响应必须与validationToken 查询参数完全匹配

azure - Graph API - 自动获取电子邮件(委派权限)

c# - 使用 Microsoft 图形 API 工作帐户发送电子邮件

email - Microsoft Graph - 仅获取最新消息内容

microsoft-graph-api - 如何从 Microsoft Graph 获取组织目录列表

Azure Active Directory appRoleAssignments "Permission being assigned was not found on application"

Azure B2C - 自动化 - 启用IEFKeySetGraphApis 功能

microsoft-graph-api - 如何通过 Microsoft Graph API 发送 s/mime 消息?

microsoft-graph-api - 为什么每当我的 MS Graph API 邮件搜索没有找到结果时,我就会收到网关超时?

microsoft-graph-api - 从 EML 附件中获取错误的内容类型