【问题标题】:Microsoft Graph Rest API Add attachment to email using c# ASP.NET MVCMicrosoft Graph Rest API 使用 c# ASP.NET MVC 将附件添加到电子邮件
【发布时间】:2016-03-07 13:53:24
【问题描述】:

我正在尝试使用 Microsoft Graph 发送带有附件的电子邮件,但是我只收到了“内部服务器错误”的响应。我尝试了几种不同的方法,但没有任何乐趣,所以希望这里有人可以提供帮助!

API 声明您可以创建和发送带有附件的电子邮件,但在我尝试首先将电子邮件创建为草稿,然后将附件添加到其中,最后发送之前遇到了问题。草稿创建良好,并且没有附件它发送良好。这是我用来将文件附加到电子邮件的代码部分:

            // Now add the attachments
        using (var client = new HttpClient())
        {
            // URL = https://graph.microsoft.com/v1.0/me/messages/{id}/attachments
            string AddAttachmentsUrl = GraphSettings.AddAttachmentsToMessageUrl;
            AddAttachmentsUrl = AddAttachmentsUrl.Replace("{id}", newMessageId);

            using (var request = new HttpRequestMessage(HttpMethod.Post, AddAttachmentsUrl))
            {
                request.Headers.Accept.Add(Json);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                string serializedData = JsonConvert.SerializeObject(current);
                // serializedData = {\"Name\":\"Test.txt\",\"ContentBytes\":\"VGVzdA0K\",\"ContentType\":\"text/plain\"}
                request.Content = new StringContent(serializedData, Encoding.UTF8, "application/json");

                using (HttpResponseMessage response = await client.SendAsync(request))
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        sendMessageResponse.Status = SendMessageStatusEnum.Fail;
                        sendMessageResponse.StatusMessage = response.ReasonPhrase;
                        return sendMessageResponse;
                    }
                }
            }
        }

我已经放入了几个 cmets,这样您就可以看到我发布到的 URL 以及我尝试发布的对象的内容。我确定我遗漏了一些明显的东西,可能与以某种方式编码 bytes[] 数据或在某处的标头中设置内容类型有关?

非常感谢任何帮助,这是我正在使用的 API 函数的链接:http://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/message_post_attachments

【问题讨论】:

    标签: c# asp.net-mvc email email-attachments microsoft-graph-api


    【解决方案1】:

    documentation 所示,请确保 json 有效负载包含值为“#microsoft.graph.fileAttachment”的“@odata.type”属性。在问题中引用的有效负载下方有更改(粗体)。

    {"@odata.type":"#microsoft.graph.fileAttachment","Name":"Test.txt","ContentBytes":"VGVzdA0K","ContentType":"文本/纯文本"}

    【讨论】:

    • 谢谢,我以为我已经尝试过了,但我错过了“odata.type”开头的@符号。放进去之后就正常了。
    猜你喜欢
    • 2019-05-05
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 2020-08-08
    相关资源
    最近更新 更多