c# - sendgrid 中的替换问题

标签 c# sendgrid

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

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

Sendgrid 错误如下:

{"from":{"email":"info@elettrone.com"},"personalizations":[{"to":[{"email":"yocax2@elettrone.com"}],"substitutions":{"-indirizzo_email-":"https://localhost:44391/Device/RegisterDevice?q=tnGdfw1EojMggP15KY39IWJGE9GkYWOTzMBsungIHrNJm6gzwc1r1zRpMZDH55%2fQ"}}],"template_id":"d-1201e63adfa04976ba9fc17212172fe9"} BadRequest Server: nginx Date: Mon, 23 Sep 2019 18:06:50 GMT Connection: keep-alive Access-Control-Allow-Origin: https://sendgrid.api-docs.io Access-Control-Allow-Methods: POST Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl Access-Control-Max-Age: 600 X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html

谁能帮帮我?

最佳答案

我解决了这个问题。指定模板 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}} 引用主题。

希望这对您有所帮助。

关于c# - sendgrid 中的替换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58062257/

相关文章:

centos - Postfix 与 SendGrid 集成,但此后停止发送电子邮件

outlook - 如何通过 SendGrid 发送 .ics 日历邀请,以便在电子邮件客户端中呈现?

node.js - 响应错误: Forbidden

c# - Xtra报告 : An object assigned to the DataSource property cannot be used

c# - 无法使用 C# visual studio 2008 将数据插入表中

c# - 如何使用更通用的 IEnumerable<T>?

使用通用接口(interface)的 C# 转换

c# - 设计状态链

javascript - 在哪里安全地存储 javascript 发送网格 api key ?

php - 无法计算出 Sendgrid SMTP (Laravel) 的用户名和密码