Почему не отправляется письмо с помощью Mailgun APi?

214
31 января 2019, 08:40

Пытаюсь отправить письмо с помощью MailGun API. Имею следующий код:

public IRestResponse SendMessage()
    {
        RestClient client = new RestClient();
        client.BaseUrl = new Uri("https://api.mailgun.net/v3");
        client.Authenticator =
            new HttpBasicAuthenticator("api",
                                        "my-api-key");
        RestRequest request = new RestRequest();
        request.AddParameter("domain", "abc.ru", ParameterType.UrlSegment);
        request.Resource = "{domain}/messages";
        request.AddParameter("from", "Excited User <mailgun@abc.ru>");
        request.AddParameter("to", "hello@mail.ru");
        request.AddParameter("subject", "Hello");
        request.AddParameter("text", "Testing some Mailgun awesomness!");
        request.Method = Method.POST;
        return client.Execute(request);
    }

И получаю JSON:

    {
      "request": null,
      "contentType": null,
      "contentLength": 0,
      "contentEncoding": null,
      "content": "",
      "statusCode": 0,
      "isSuccessful": false,
      "statusDescription": null,
      "rawBytes": null,
      "responseUri": null,
      "server": null,
      "cookies": [
       ],
      "headers": [
      ],
      "responseStatus": 2,
      "errorMessage": "Operation is not supported on this platform.",
      "errorException": {
        "ClassName": "System.PlatformNotSupportedException",
        "Message": "Operation is not supported on this platform.",
        "Data": null,
        "InnerException": null,
        "HelpURL": null,
        "StackTraceString": "   at System.Net.SystemWebProxy.GetProxy(Uri 
    destination)\r\n   at 
    System.Net.ServicePointManager.ProxyAddressIfNecessary(Uri& address, 
    IWebProxy proxy)\r\n   at 
    System.Net.ServicePointManager.FindServicePoint(Uri address, IWebProxy 
    proxy)\r\n   at System.Net.HttpWebRequest.get_ServicePoint()\r\n   at 
    RestSharp.Http.ConfigureWebRequest(String method, Uri url)\r\n   at 
    RestSharp.Http.PostPutInternal(String method)\r\n   at 
    RestSharp.Http.AsPost(String httpMethod)\r\n   at 
    RestSharp.RestClient.DoExecuteAsPost(IHttp http, String method)\r\n   at 
    RestSharp.RestClient.Execute(IRestRequest request, String httpMethod, 
    Func`3 getResponse)",
        "RemoteStackTraceString": null,
        "RemoteStackIndex": 0,
        "ExceptionMethod": null,
        "HResult": -2146233031,
        "Source": "System.Net.Requests",
        "WatsonBuckets": null
      },
      "protocolVersion": null
    }
Answer 1

Ваш код работает корректно. Проблема возникает в библиотеке RestSharp: скорее всего у вас старая или косячная версия. Подобная проблема с RestSharp обсуждалась здесь.

Могу посоветовать готовую библиотеку для работы с Mailgun API - она не тянет за собой никаких лишних зависимостей вроде RestSharp, и довольно проста в использовании:

var mailgun = new Mailgun("sending-domain.com", "api-key");
var result = await mailgun.SendMessageAsync(
                new EmailAddress("support@your-domain.com", "Support Team"), // From
                new EmailAddress("user@gmail.com"),                          // To
                "Welcome",                                                   // Subject
                "Welcome, dear user!");                                      // Message
if (!result.Successful)
    Console.WriteLine(result.ErrorMessage);
READ ALSO
Создание объекта по имени класса [дубликат]

Создание объекта по имени класса [дубликат]

На данный вопрос уже ответили:

165
Создание dll с Roslyn

Создание dll с Roslyn

Пробую создать dll библиотеку c RoslynДобавил все библиотеки с NuGet для работы с Roslyn

177
Выделение объекта по контуру

Выделение объекта по контуру

Какие есть способы выделения(либо подсветки, а еще лучше подсветки только контура) объекта в игре при наведении на него курсораЕсли использовать...

179
c# сокеты клиент-сервер

c# сокеты клиент-сервер

У меня небольшая проблемка в работе с клиент-сервером

158