[英]Get attachments from Office365 email using Microsoft Graph
I am connecting to an Office365 mailbox in my organisation using the Graph API.我正在使用 Graph API 连接到我组织中的 Office365 邮箱。
It connects fine, it returns the first 10 unread emails, the.HasAttachments if statement only runs when there is an attachment but item.Attachments or item.Atttachments.CurrentPage is erroring with 'Object reference not set to an instance of an object.'它连接良好,它返回前 10 封未读电子邮件,.HasAttachments if 语句仅在有附件时运行,但 item.Attachments 或 item.Atttachments.CurrentPage 错误并显示“对象引用未设置为 object 的实例。”
My aim is to read unread emails, download/parse the attachment and then mark the email as read.我的目标是阅读未读电子邮件,下载/解析附件,然后将 email 标记为已读。
Can anyone advise where I'm going wrong?谁能告诉我哪里出错了?
// Auth code omitted for brevity...
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var messages = await graphClient.Users["ipaqpc@mymail.com"].Messages
.Request()
.Filter("isRead eq false")
.GetAsync();
Console.WriteLine(messages.Count); // Returns "10".
foreach (Microsoft.Graph.Message item in messages.CurrentPage)
{
Console.WriteLine(item.Sender.EmailAddress.Address); // Prints email address.
if(item.HasAttachments == true)
{
Console.WriteLine("Has attachment"); // Prints when email has attachment.
foreach (var attachment in item.Attachments.CurrentPage) // Errors
{
Console.WriteLine(attachment.Name);
}
}
}```
The default behavior is not to fetch attachment data.默认行为是不获取附件数据。 You have to ask for it and you have two options:你必须要求它,你有两个选择:
Option 1: You ask for it throught attachment id.选项 1:您通过附件 ID 要求它。
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var attachment = await graphClient.Me.Messages["{message-id}"].Attachments["{attachment-id}"]
.Request()
.GetAsync();
Option 2: You include a $expand on the Request Url.选项 2:您在请求 Url 中包含 $expand。
GET https://graph.microsoft.com/v1.0/me/messages/AAMkADA1M-zAAA=/attachments/AAMkADA1M-CJKtzmnlcqVgqI=/?$expand=microsoft.graph.itemattachment/item
So you have to modify your actual implementation to something like this所以你必须将你的实际实现修改为这样的
var message = await graphClient.Users["ipaqpc@mymail.com"].Messages[messageId]
.Request()
.Expand("attachments")
.GetAsync();
Or this或这个
var message = await graphClient.Users["ipaqpc@mymail.com"].Messages
.Request()
.Expand("attachments")
.GetAsync();
Documentation:文档:
https://docs.microsoft.com/en-us/graph/api/attachment-get?view=graph-rest-1.0&tabs=http https://docs.microsoft.com/en-us/graph/api/attachment-get?view=graph-rest-1.0&tabs=http
https://docs.microsoft.com/en-us/graph/sdks/create-requests?tabs=CS https://docs.microsoft.com/en-us/graph/sdks/create-requests?tabs=CS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.