使用Microsoft Graph SDK下载电子邮件附件的原始内容。

huangapple go评论72阅读模式
英文:

Download raw content of email attachment using Microsoft Graph SDK

问题

SDK中是否有一种方法允许下载电子邮件附件内容字节?

基本上,它应该根据https://learn.microsoft.com/en-us/graph/api/attachment-get?view=graph-rest-1.0&tabs=csharp#example-6-get-the-raw-contents-of-a-file-attachment-on-a-message的请求URL只需附加/$value,但我在SDK中没有看到这样的功能。

我能找到的最接近的是:

await graphClient.Users[userId].Messages[messageId].Attachments[attachmentId].GetAsync()

我期望会有类似于Attachments[attachmentId].Content.GetAsync()的方法或类似的东西。

Microsoft.Graph 5.13.0

英文:

Is there a method that allows to download the email attachment content bytes using the SDK?

Basically, it should just append /$value the request URL according to https://learn.microsoft.com/en-us/graph/api/attachment-get?view=graph-rest-1.0&tabs=csharp#example-6-get-the-raw-contents-of-a-file-attachment-on-a-message , but I don't see such feature in SDK

The closest I could get is

await graphClient.Users[userId].Messages[messageId].Attachments[attachmentId].GetAsync()

I would expect Attachments[attachmentId].Content.GetAsync() or something

Microsoft.Graph 5.13.0

答案1

得分: 2

SDK v5仍不支持下载消息附件。解决方法可以是:

var requestInfo = graphClient.Users["{user_id}"]
                             .Messages["{message_id}"]
                             .Attachments["{attachment_id}"]
                             .ToGetRequestInformation();
requestInfo.UrlTemplate = requestInfo.UrlTemplate
                           .Insert(requestInfo.UrlTemplate.LastIndexOf('{'), "/$value");
var attachmentStream = await graphClient.RequestAdapter.SendPrimitiveAsync<Stream>(requestInfo);
英文:

It's still not supported by SDK v5 to download message's attachment. The workaround can be

var requestInfo = graphClient.Users[&quot;{user_id}&quot;]
                             .Messages[&quot;{message_id}&quot;]
                             .Attachments[&quot;{attachment_id}&quot;]
                             .ToGetRequestInformation();
requestInfo.UrlTemplate = requestInfo.UrlTemplate
                           .Insert(requestInfo.UrlTemplate.LastIndexOf(&#39;{&#39;), &quot;/$value&quot;);
var attachmentStream = await graphClient.RequestAdapter.SendPrimitiveAsync&lt;Stream&gt;(requestInfo);

答案2

得分: 0

我无法找到通过SDK执行此操作的代码片段,所以我通过结合Graph客户端和自定义HttpClient调用编写了自己的代码。

AttachmentsRequestBuilder GetAttachmentsList(string id) =>
    graphClient.Users[userId].Messages[id].Attachments;

var attachmentList = await GetAttachmentsList(messageId)
    .GetAsync(cancellationToken: cancellationToken);

if (attachmentList?.Value != null)
{
    foreach (var attachmentItem in attachmentList.Value)
    {
        var attachmentRequest = GetAttachmentsList(messageId)[attachmentItem.Id];
        var getRequestInfo = attachmentRequest.ToGetRequestInformation();
        var attachmentUri = getRequestInfo.URI + "/$value";

        using var client = httpClientFactory.CreateClient();

        client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", await GetToken());
        var response = await client.GetAsync(attachmentUri, cancellationToken);

        var file = await response.Content.ReadAsByteArrayAsync(cancellationToken);
    }
}

// GetToken方法
private async Task<string> GetToken()
{
    using var client = httpClientFactory.CreateClient();

    var @params = new Dictionary<string, string>()
    {
        { "client_id", clientId },
        { "client_secret", clientSecret },
        { "scope", "https://graph.microsoft.com/.default" },
        { "grant_type", "client_credentials" },
    };

    var response = await
        client.PostAsync($"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token",
            new FormUrlEncodedContent(@params));

    response.EnsureSuccessStatusCode();

    using var sr = new StreamReader(await response.Content.ReadAsStreamAsync());
    var body = await sr.ReadToEndAsync();
    var jobject = JObject.Parse(body);

    return jobject["access_token"]!.ToString();
}

这是您提供的代码的中文翻译。

英文:

I could not find a snippet to do it via SDK, so I wrote my own by combining Graph client and custom HttpClient calls.

AttachmentsRequestBuilder GetAttachmentsList(string id) =&gt;
    graphClient.Users[userId].Messages[id].Attachments;

var attachmentList = await GetAttachmentsList(messageId)
    .GetAsync(cancellationToken: cancellationToken);

if (attachmentList?.Value != null)
{
    foreach (var attachmentItem in attachmentList.Value)
    {
        var attachmentRequest = GetAttachmentsList(messageId)[attachmentItem.Id];
        var getRequestInfo = attachmentRequest.ToGetRequestInformation();
        var attachmentUri = getRequestInfo.URI + &quot;/$value&quot;;

        using var client = httpClientFactory.CreateClient();

        client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue(&quot;Bearer&quot;, await GetToken());
        var response = await client.GetAsync(attachmentUri, cancellationToken);

        var file = await response.Content.ReadAsByteArrayAsync(cancellationToken);
    }
}

GetToken method

private async Task&lt;string&gt; GetToken()
{
    using var client = httpClientFactory.CreateClient();

    var @params = new Dictionary&lt;string, string&gt;()
    {
        { &quot;client_id&quot;, clientId },
        { &quot;client_secret&quot;, clientSecret },
        { &quot;scope&quot;, &quot;https://graph.microsoft.com/.default&quot; },
        { &quot;grant_type&quot;, &quot;client_credentials&quot; },
    };

    var response = await
        client.PostAsync($&quot;https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token&quot;,
            new FormUrlEncodedContent(@params));

    response.EnsureSuccessStatusCode();

    using var sr = new StreamReader(await response.Content.ReadAsStreamAsync());
    var body = await sr.ReadToEndAsync();
    var jobject = JObject.Parse(body);

    return jobject[&quot;access_token&quot;]!.ToString();
}

huangapple
  • 本文由 发表于 2023年7月17日 23:19:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76705913.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定