【问题标题】:Issue with substitution in sendgridsendgrid 中的替换问题
【发布时间】:2020-01-23 12:18:39
【问题描述】:

我必须使用 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;
    }

发送过程总是失败可能是因为在第三种方法中我分离了 dynamicTemplateData 和替换。我必须发送一条引用存储在 sendgrid 中的模板的消息,并且我没有将其传递给方法。

Sendgrid 错误如下:

{"发件人":{"email":"info@elettrone.com"},"个性化":[{"to":[{"email":"yocax2@elettrone.com"}],"替换":{"-indirizzo_email-":"https://localhost:44391/Device/RegisterDevice?q=tnGdfw1EojMggP15KY39IWJGE9GkYWOTzMBsungIHrNJm6gzwc1r1zRpMZDH55%2fQ"}}],"template_id":"d-1201e63adfa04976ba9fc17212172fe9"} 错误的请求 服务器:nginx 日期:2019 年 9 月 23 日星期一 18:06:50 GMT 连接:保持活动 访问控制允许来源:https://sendgrid.api-docs.io 访问控制允许方法:POST Access-Control-Allow-Headers:授权、Content-Type、代表、x-sg-elas-acl 访问控制最大年龄:600 X-No-CORS-原因:https://sendgrid.com/docs/Classroom/Basics/API/cors.html

谁能帮帮我?

【问题讨论】:

  • 您得到的实际异常是什么?
  • @silleknarf : 我收到 SendGrid BadRequest 异常。
  • @mason 这不是 .NET 异常,而是我从 SendGrid 响应中得出的异常。
  • @mason:这是一个 SendGrid BadRequest 失败消息。它不会发送电子邮件,但程序不会崩溃。
  • @mason :我将其添加到帖子中。

标签: c# sendgrid


【解决方案1】:

我解决了这个问题。指定模板 ID 时,替换必须与 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}} 引用主题。

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2016-07-26
    • 2016-02-27
    • 2016-11-10
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多