【问题标题】:How to Add Custom variables to SendGrid email via API C# and Template如何通过 API C# 和模板将自定义变量添加到 SendGrid 电子邮件
【发布时间】:2014-11-11 07:27:11
【问题描述】:

我试图弄清楚如何将变量添加到已在 sendgrid 模板引擎中创建的现有模板(例如:动态 Web 链接或名称),我不确定如何使用 SendGrid C# .NET 库来执行此操作。我想知道是否有人可以帮助我。

// Create the email object first, then add the properties.
SendGridMessage myMessage = new SendGridMessage();

myMessage.AddTo("test@test.com");
myMessage.From = new MailAddress("test@test.com", "Mr test");
myMessage.Subject = " ";

var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
myMessage.Html = "<p></p> ";

myMessage.EnableTemplate("<p> <% body %> Hello</p>");
myMessage.EnableTemplateEngine("9386b483-8ad4-48c2-9ee3-afc7618eb56a");
var identifiers = new Dictionary<String, String>();
identifiers["USER_FULLNAME"] = "Jimbo Jones";
identifiers["VERIFICATION_URL"] = "www.google.com";
myMessage.AddUniqueArgs(identifiers);

// Create credentials, specifying your user name and password.
var credentials = new NetworkCredential("username", "password");
// Create an Web transport for sending email.
var transportWeb = new Web(credentials);
// Send the email.
transportWeb.Deliver(myMessage);

【问题讨论】:

    标签: c# asp.net sendgrid


    【解决方案1】:

    我的电子邮件

    Hello -REP-
    
    <%body%>
    
    Fotter
    

    我的 C# 代码

    myMessage.AddSubstitution("-REP-", substitutionValues);
    

    工作完美!!!

    【讨论】:

      【解决方案2】:

      我找到了解决办法:

      replacementKey = "*|VERIFICATION_URL|*";
      substitutionValues = new List<string> { VERIFICATION_URL };
      
      myMessage.AddSubstitution(replacementKey, substitutionValues);
      

      【讨论】:

      • 您必须从有问题的代码中删除某些内容?
      • 我不明白你的意思。?
      • 忽略我的评论,我解决了我的问题。谢谢,
      • Jimbo 没有使用“标识符”和 AddUniqueArgs(用于向电子邮件添加额外字段以进行识别),而是使用 AddSubstitution,它替换模板中的文本。
      【解决方案3】:

      我使用了以下方法。请注意,您必须提供 mail.Textmail.Html 值 - 如示例中所示,我使用空字符串和 &lt;p&gt;&lt;/p&gt; 标记。您的 SendGrid 模板还必须包含默认的 &lt;%body%&gt;&lt;%subject%&gt; 标记,尽管它们将替换为在 mail.Textmail.Html 属性中指定的实际主题和正文值。

      public void Send(string from, string to, string subject, IDictionary<string, string> replacementTokens, string templateId)
      {
        var mail = new SendGridMessage
        {
          From = new MailAddress(from)
        };
      
        mail.AddTo(to);
        mail.Subject = subject;
      
        // NOTE: Text/Html and EnableTemplate HTML are not really used if a TemplateId is specified
        mail.Text = string.Empty;
        mail.Html = "<p></p>";
        mail.EnableTemplate("<%body%>");
      
        mail.EnableTemplateEngine(templateId);
      
        // Add each replacement token
        foreach (var key in replacementTokens.Keys)
        {
          mail.AddSubstitution(
            key,
            new List<string>
              {
                replacementTokens[key]
              });
        }
      
        var transportWeb = new Web("THE_AUTH_KEY");
        var result = transportWeb.DeliverAsync(mail);
      }
      

      然后可以这样调用:

      Send(
      "noreply@example.com", 
      "TO_ADDRESS", 
      "THE SUBJECT", 
      new Dictionary<string, string> { 
      { "@Param1!", "Parameter 1" }, 
      { "@Param2!", "Parameter 2" } }, 
      "TEMPLATE_GUID");
      

      【讨论】:

        【解决方案4】:

        做了很多 RND。我下面的代码工作正常并经过测试。

                    SendGridMessage myMessage = new SendGridMessage();
                    myMessage.AddTo(email);
                    myMessage.AddBcc("MyEmail@gmail.com");
                    myMessage.AddBcc("EmailSender_CC@outlook.com");
                    myMessage.From = new MailAddress("SenderEmail@outlook.com", "DriverPickup");
                    //myMessage.Subject = "Email Template Test 15.";
                    myMessage.Headers.Add("X-SMTPAPI", GetMessageHeaderForWelcome("MyEmail@Gmail.com", callBackUrl));
                    myMessage.Html = string.Format(" ");
        
                    // Create an Web transport for sending email.
                    var transportWeb = new Web(SendGridApiKey);
        
                    // Send the email, which returns an awaitable task.
                    transportWeb.DeliverAsync(myMessage);
        

        我已经创建了获取 JSON 标头的单独方法

        private static string GetMessageHeaderForWelcome(string email, string callBackUrl)
            {
        
                var header = new Header();
                //header.AddSubstitution("{{FirstName}}", new List<string> { "Dilip" });
                //header.AddSubstitution("{{LastName}}", new List<string> { "Nikam" });
                header.AddSubstitution("{{EmailID}}", new List<string> { email });
                header.AddSubstitution("-VERIFICATIONURL-", new List<string>() { callBackUrl });
                //header.AddSubstitution("*|VERIFICATIONURL|*", new List<string> { callBackUrl });
                //header.AddSubstitution("{{VERIFICATIONURL}}", new List<string> { callBackUrl });
                header.AddFilterSetting("templates", new List<string> { "enabled" }, "1");
                header.AddFilterSetting("templates", new List<string> { "template_id" }, WelcomeSendGridTemplateID);
                return header.JsonString();
        
            }
        

        下面是我在 HTML Sendgrid 模板中使用的代码。

        <div>Your {{EmailID}} register. Please <a class="btn-primary" href="-VERIFICATIONURL-">Confirm email address</a></div>
        

        如果有任何疑问,请告诉我。

        对于内联 HTML 替换,您需要使用 -YourKeyForReplace-;对于文本替换,您需要使用 {{UserKeyForReplace}}

        【讨论】:

        • 我们可以在 C# 中使用 Using 语句创建 SendGridMessage 的对象吗?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-22
        相关资源
        最近更新 更多