检索附件名称并下载附件

Retrieving attachment names and downloading the attachments

提问人:Tamtomo Abdi Negoro 提问时间:11/14/2023 最后编辑:Tamtomo Abdi Negoro 更新时间:11/14/2023 访问量:31

问:

希望这里有人能启发我如何使用 Microsoft Graph 从电子邮件中下载附件。我正在尝试从具有特定主题的 Office 365 邮件中自动下载和处理附件。到目前为止,我已经设法迭代了这些消息并将它们放在一个名为messageList的列表中,但尚未成功检索每封邮件中的附件名称并下载它们。这是我的代码:

     var messages = await graphClient
             .Users[userEmail]
             .MailFolders[folderId]
             .Messages
             .GetAsync((requestConfiguration) =>
             {
                 //requestConfiguration.QueryParameters.Count = true;
                 //requestConfiguration.Headers.Add("ConsistencyLevel", "eventual");
                 requestConfiguration.QueryParameters.Filter = 
                 "receivedDateTime ge 1900-01-01T00:00:00Z and (from/emailAddress/address) eq '[email protected]'";
                 requestConfiguration.QueryParameters.Orderby = new string[] { "receivedDateTime desc"};
             });
var messageList = new List<Message>();
     var pageIterator = PageIterator<Message, MessageCollectionResponse>.
         CreatePageIterator(graphClient, messages, (message) =>
     {
         
         //Console.WriteLine(message.Subject);
         messageList.Add(message);
         return true;
     });
     await pageIterator.IterateAsync();
     while (pageIterator.State != PagingState.Complete)
     {
         await pageIterator.IterateAsync();
     }
     foreach (var m in messageList)
     {
         if (m.HasAttachments == true)
         {
             var attachments=m.Attachments;
             if (attachments != null)
             {
                 foreach (var attachment in attachments)
                 {
    
                     Console.WriteLine("Attachment Name : " + attachment.Name);
                 }
             }
             Console.WriteLine(m.Subject + " Has attachment(s)");
         }
    
     }

如果我在 Autos 中查看 m 对象,它的 Attachment 属性为 null。enter image description here请帮忙,尤其是在下载文件时。提前感谢您的帮助。

C# Outlook Microsoft-Graph-API Office365 电子邮件附件

评论

0赞 user2250152 11/14/2023
你能提供更多代码吗?至少你如何创建消息属性或你发送的读取消息的请求
0赞 Tamtomo Abdi Negoro 11/14/2023
@user2250152,我已经编辑了我的问题以添加您的要求。
0赞 Luuk 11/14/2023
您正在循环 mesagelist ()。我认为您应该遍历一条消息以获取所有附件?foreach (var m in messageList)
0赞 Tamtomo Abdi Negoro 11/14/2023
@Luuk如果我选择循环访问消息,还有什么可循环的呢?每个邮件附件对象都是 null,而它不应该是 null,因为它有附件,我确保只检索带有附件的邮件

答:

1赞 user2250152 11/14/2023 #1

默认情况下不包括附件,您需要使用 expand 告诉服务器响应中应包含附件。然后,您需要强制转换每个附件才能读取数据FileAttachment

var messages = await graphClient
 .Users[""]
 .MailFolders[""]
 .Messages
 .GetAsync((requestConfiguration) =>
 {
     requestConfiguration.QueryParameters.Filter =
     "receivedDateTime ge 1900-01-01T00:00:00Z and (from/emailAddress/address) eq '[email protected]'";
     requestConfiguration.QueryParameters.Orderby = new string[] { "receivedDateTime desc" };
     // return also attachments
     requestConfiguration.QueryParameters.Expand = new string[] { "attachments" };
 });
var messageList = new List<Message>();
var pageIterator = PageIterator<Message, MessageCollectionResponse>.
    CreatePageIterator(graphClient, messages, (message) =>
    {
        //Console.WriteLine(message.Subject);
        messageList.Add(message);
        return true;
    });
await pageIterator.IterateAsync();
while (pageIterator.State != PagingState.Complete)
{
    await pageIterator.IterateAsync();
}
foreach (var m in messageList)
{
    if (m.HasAttachments == true)
    {
        foreach (var attachment in m.Attachments)
        {
            Console.WriteLine("Attachment Name : " + attachment.Name);
            if (attachment is FileAttachment fileAttachment)
            {
                // content is base64 encoded bytes
                var base64String = Encoding.ASCII.GetString(fileAttachment.ContentBytes);
                var bytes = Convert.FromBase64String(base64String);
                File.WriteAllBytes("path", bytes);
            }
        }
    }
    Console.WriteLine(m.Subject + " Has attachment(s)");
}

从性能的角度来看,过滤带有附件的邮件会更好

var messages = await graphClient
 .Users[""]
 .MailFolders[""]
 .Messages
 .GetAsync((requestConfiguration) =>
 {
     requestConfiguration.QueryParameters.Filter =
     "receivedDateTime ge 1900-01-01T00:00:00Z and (from/emailAddress/address) eq '[email protected]' and hasAttachments eq true";
     requestConfiguration.QueryParameters.Orderby = new string[] { "receivedDateTime desc" };
 });

对于每封邮件,请单独调用以返回附件

var attachments = await graphClient
 .Users[""]
 .MailFolders[""]
 .Messages["{message_id}"].Attachments.GetAsync()

评论

0赞 Tamtomo Abdi Negoro 11/14/2023
非常感谢马丁,你摇滚。伙计,Microsoft真的不一样了,哈哈。下次再次使用 Microsoft API 时,我会检查查询参数