如何在C#应用程序中使用Outlook Rest API发送邮件?

问题描述 投票:-1回答:1

我想通过Outlook Rest API发送邮件:

我在https://docs.microsoft.com/en-us/previous-versions/office/office-365-api/api/version-2.0/mail-rest-operations#SendMessageOnTheFly处研究信息

我使用Microsoft.Identity.ClientAuthorization并获得令牌。这个我的函数返回一个令牌好:

string[] scopes = new string[] { "user.read","Mail.send" };
private async void GetToken()
{
    AuthenticationResult authResult = null;
    var app = App.PublicClientApp;

    var accounts = await app.GetAccountsAsync();
    var firstAccount = accounts.FirstOrDefault();

    authResult = await app.AcquireTokenSilent(scopes, firstAccount).ExecuteAsync(); 

    if (authResult != null)
    {
        string token= authResult.AccessToken;               
        await SendMail(token);
    }
}

我正在使用以上的token发送邮件

public async Task<string> SendMail(string token)
{
    string url = "https://outlook.office.com/api/v2.0/me/sendmail";
    var httpClient = new System.Net.Http.HttpClient();
    System.Net.Http.HttpResponseMessage response;

    try
    {
        var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post , url);
        //Add the token in Authorization header
        request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

        var strjs = @"{
                  ""Message"": {
                    ""Subject"": ""Meet for lunch?"",
                    ""Body"": {
                      ""ContentType"": ""Text"",
                      ""Content"": ""The new cafeteria is open.""
                    },
                    ""ToRecipients"": [
                      {
                        ""EmailAddress"": {
                          ""Address"": ""[email protected]""
                        }
                      }
                    ],
                    ""Attachments"": [
                      {
                        ""@odata.type"": ""#Microsoft.OutlookServices.FileAttachment"",
                        ""Name"": ""menu.txt"",
                        ""ContentBytes"": ""bWFjIGFuZCBjaGVlc2UgdG9kYXk=""
                      }
                    ]
                  },
                  ""SaveToSentItems"": ""false""
                }";

        request.Content = new StringContent(strjs,
            Encoding.UTF8, "application/json");

        response = await httpClient.SendAsync(request);
        var content = await response.Content.ReadAsStringAsync();
        return content;
    }
    catch (Exception ex)
    {
        return ex.ToString();
    }
}

服务器响应错误:

{"error":{"code":"InvalidMsaTicket","message":"ErrorCode: 'PP_E_RPS_CERT_NOT_FOUND'. Message: ' Internal error: spRPSTicket->ProcessToken failed. Failed to call CRPSDataCryptImpl::UnpackData: Internal error: Failed to decrypt data. :Failed to get session key. RecipientId=293577. spCache->GetCacheItem returns error.:Cert Name: (null). SKI: 3bd72187c709b1c40b994f8b496a5b9ebd2f9b0c...'","innerError":{"requestId":"f691aeb0-1c32-4302-875a-88a9f6528b9f","date":"2019-12-12T08:27:10"}}}

缺少什么?

如何在C#应用程序中使用Outlook Rest API发送邮件?谢谢。


由个人帐户创建的我的应用程序ID。这是问题吗?

我正在尝试获取用户的个人资料,它返回确定:

public async Task<string> GetHttpContentWithToken(string token)
{
    string url= "https://graph.microsoft.com/v1.0/me";
    var httpClient = new System.Net.Http.HttpClient();
    System.Net.Http.HttpResponseMessage response;            
    var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
    //Add the token in Authorization header
    request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
    response = await httpClient.SendAsync(request);
    var content = await response.Content.ReadAsStringAsync();
    return content;
}

结果:

{"@odata.context":"https://graph.microsoft.com/v1.0/$metadata#users/$entity","displayName":"koi test","surname":"test","givenName":"koi","id":"5d32f40f9f38b408","userPrincipalName":"[email protected]","businessPhones":[],"jobTitle":null,"mail":null,"mobilePhone":null,"officeLocation":null,"preferredLanguage":null}
c# outlook outlook-restapi
1个回答
0
投票

此范围将与图形API一起使用:

string[] scopes = new string[] { "user.read","Mail.send" };

为了使Outlook Rest API正常工作,我将范围更改为:

 string[] scopes = new string[] { "https://outlook.office.com/user.read", "https://outlook.office.com/Mail.send" };
© www.soinside.com 2019 - 2024. All rights reserved.