我已经使用 microsoft graph rest api 成功获取了收件箱中的邮件列表,但我很难理解有关如何从邮件下载附件的文档。
例如:这个问题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 的 key ,我猜这是文件的加密内容。
最佳答案
对于attachment
resource的file 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/