使用Microsoft Graph C#下载.eml文件

问题描述

我在使用Microsoft Graph时遇到问题。我想下载特定电子邮件中的附件。我已验证此后返回的对象类型:

@H_404_3@ var attachments = graphClient.Me.Messages[msg.Id].Attachments.Request().GetAsync().Result;
 foreach(var item in attachments) {
         var current_attachment = graphClient.Me.Messages[msg.Id].Attachments[item.Id].Request().GetAsync().Result;
}

是附件类型的对象。 现在,我想下载该对象(current_attachment),但是我看到属性ContentBytes不可用。 我试图将对象强制转换为FileAttachment,但是会引发异常。

谢谢。

解决方法

这应该很简单。具体来说:

https://docs.microsoft.com/en-us/graph/outlook-get-mime-message

即使Outlook不会以MIME格式保存邮件,也有 获得MIME格式的Outlook邮件正文的两种方法:

您可以将$ value段添加到该行的get-message操作中 信息。如果邮件附加到Outlook项目或组帖子中, 您可以将$ value段添加到该字段的get-attachment操作中 项目或群组发布。无论哪种情况,您的应用都必须具有适当的 可以访问Outlook项目或组帖子以进行申请的权限 get-message或get-attachment操作。

然后您可以将邮件正文内容保存在.EML文件中并附加 文件记录到业务系统中的记录,例如CRM,ERP, 和错误跟踪。

这里是一个例子:

https://docs.microsoft.com/en-us/graph/api/message-get?view=graph-rest-1.0&tabs=csharp

获取登录用户的邮箱中邮件的MIME内容。

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var stream = await graphClient.Me.Messages["4aade2547798441eab5188a7a2436bc1"].Content
  .Request()
  .GetAsync();

您可以像这样将“流”写入磁盘文件:

string path = @"\my\path\myfile.eml";
using(FileStream outputFileStream = new FileStream(path,FileMode.Create)) 
{  
    stream.CopyTo(outputFileStream);  
}  

生成的.eml文件将是完整的电子邮件,包括所有附件。