我已经使用 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 的密钥,我猜它是文件的加密内容。
对于attachment
资源的文件类型 contentBytes
属性返回
文件的 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
库
我已经能够获得 contentBytes 属性。我正在寻找使用它的解决方案并保存附件
@ifranharun,在 Node.js 中保存到本地文件?
不,我使用的是一个只有 Jquery 的简单网页。我也可以使用其他库。但没有 NodeJs
@ifranharun,你能不能用一个最小的例子来更新你的问题,说明什么不起作用?
@irfanharun,答案已更新(请参阅更新部分)