簡體   English   中英

Microsoft Graph Rest API使用c#ASP.NET MVC將附件添加到電子郵件

[英]Microsoft Graph Rest API Add attachment to email using c# ASP.NET MVC

我正在嘗試使用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;
                    }
                }
            }
        }

我在其中添加了一些注釋,以便您可以看到要發布到的URL以及嘗試發布的對象的內容。 我確定我缺少明顯的東西,也許與以某種方式編碼bytes []數據或在某處的標頭中設置內容類型有關?

非常感謝您的幫助,這是我使用的API函數的鏈接: http : //graph.microsoft.io/zh-cn/docs/api-reference/v1.0/api/message_post_attachments

文檔中所示 ,請確保JSON負載包含值為“#microsoft.graph.fileAttachment”的“ @ odata.type”屬性。 問題中引用的有效負載下方有更改(粗體)。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM