Проблема с заменой в sendgrid - PullRequest
2 голосов
/ 23 сентября 2019

Я должен отправить письмо с заменой, используя sendgrid.Я использую следующий код:

    public async Task SendConfirmationMailAsync(UserCreateViewModel model, string domain, ApplicationUser user)
    {
        string q = _encryption.EncryptText(model.Email + "|" + model.Password, _configuration["Security:EncryptionKey"]);
        string encryptdetexturl = HttpUtility.UrlEncode(q);
        string url = domain + "/Device/RegisterDevice?q=" + encryptdetexturl;


        Dictionary<string, string> substitution = new Dictionary<string, string>();
        substitution.Add("-indirizzo_email-", url);

        await _emailService.SendEmailAsync(user.Email, "d-1201e63adfa04976ba9fc17212172fe9", substitution);
    }

, который вызывает

    public async Task SendEmailAsync(ApplicationUser applicationUser, string templateId)
    {
        var apiKey = _configuration["Email:apikey"];

        var client = new SendGridClient(apiKey);

        var from = new EmailAddress(_configuration["Email:Email"]);
        var to = new EmailAddress(applicationUser.Email);

        var substitutions = GetReplacement(applicationUser);

        var msg = MailHelper.CreateSingleTemplateEmail(from, to, templateId, null,substitutions);

        var response = await client.SendEmailAsync(msg);

        Trace.WriteLine(msg.Serialize());
        Trace.WriteLine(response.StatusCode);
        Trace.WriteLine(response.Headers);
    }

, который вызывает

    public static SendGridMessage CreateSingleTemplateEmail(
                                                    EmailAddress from,
                                                    EmailAddress to,
                                                    string templateId,
                                                    object dynamicTemplateData,
                                                    Dictionary<string, string> substitutions)
    {
        if (string.IsNullOrWhiteSpace(templateId))
        {
            throw new ArgumentException($"{nameof(templateId)} is required when creating a dynamic template email.", nameof(templateId));
        }

        var msg = new SendGridMessage();
        msg.SetFrom(from);
        msg.AddTo(to);
        msg.TemplateId = templateId;

        if (dynamicTemplateData != null)
        {
            msg.SetTemplateData(dynamicTemplateData);
        }

        if (substitutions != null)
        {
            msg.AddSubstitutions(substitutions);
        }

        return msg;
    }

Процесс отправки всегда терпит неудачу, вероятно, потому что в третьем методе I 'Мы разделили dynamicTemplateData и замены.Мне нужно отправить сообщение, которое относится к храму, хранящемуся в sendgrid, и мне не нужно передавать его методу.

Ошибка Sendgrid следующая:

{"от": { "электронная почта": "info@elettrone.com"}, "" персонализации: [{ "к": [{ "электронная почта": "yocax2@elettrone.com"}], "замены": {»-indirizzo_email - ":" https://localhost:44391/Device/RegisterDevice?q=tnGdfw1EojMggP15KY39IWJGE9GkYWOTzMBsungIHrNJm6gzwc1r1zRpMZDH55%2fQ"}}],"template_id":"d-1201e63adfa04976ba9fc17212172fe9"} BadRequest Сервер: nginx Дата: понедельник, 23 сентября 2019 18:06:50 GMT Соединение: keep-alive Access-Control-Allow-Origin: https://sendgrid.api -docs.io Методы контроля доступа-разрешения: заголовки контроля доступа POST: авторизация, тип контента, от имени, x-sg-elas-acl-контроль доступа-макс-возраст: 600X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html

Может кто-нибудь помочь мне, пожалуйста?

1 Ответ

1 голос
/ 24 сентября 2019

Я решил проблему.При указании идентификатора шаблона замены должны передаваться с dynamicTemplateData, а не с заменами.

Вот пример использования, предоставленный Sendgrid на https://github.com/sendgrid/sendgrid-csharp/blob/master/USE_CASES.md#with-mail-helper-class:

using Newtonsoft.Json;
using SendGrid;
using SendGrid.Helpers.Mail;
using System.Threading.Tasks;
using System;

namespace Example
{
  internal class Example
  {
    private static void Main()
    {
        Execute().Wait();
    }

    static async Task Execute()
    {
        var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");
        var client = new SendGridClient(apiKey);
        var msg = new SendGridMessage();
        msg.SetFrom(new EmailAddress("test@example.com", "Example User"));
        msg.AddTo(new EmailAddress("test@example.com", "Example User"));
        msg.SetTemplateId("d-d42b0eea09964d1ab957c18986c01828");

        var dynamicTemplateData = new ExampleTemplateData
        {
            Subject = "Hi!",
            Name = "Example User",
            Location = new Location
            {
                City = "Birmingham",
                Country = "United Kingdom"
            }
        };

        msg.SetTemplateData(dynamicTemplateData);
        var response = await client.SendEmailAsync(msg);
        Console.WriteLine(response.StatusCode);
        Console.WriteLine(response.Headers.ToString());
        Console.WriteLine("\n\nPress any key to exit.");
        Console.ReadLine();
    }

    private class ExampleTemplateData
    {
        [JsonProperty("subject")]
        public string Subject { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("location")]
        public Location Location { get; set; }
    }

    private class Location
    {
        [JsonProperty("city")]
        public string City { get; set; }

        [JsonProperty("country")]
        public string Country { get; set; }
    }
  }
}

В шаблоне, например, тему, на которую вы должны ссылаться с {{subject}}.

Надеюсь, эта помощь.

...