如何通过API C#和Template向SendGrid电子邮件添加自定义变量

时间:2014-09-17 09:59:32

标签: c# asp.net sendgrid

我试图弄清楚如何将变量添加到已在sendgrid模板引擎中创建的现有模板(例如:动态链接或名称),我不确定如何使用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);

4 个答案:

答案 0 :(得分:10)

我的电子邮件

Hello -REP-

<%body%>

Fotter

我的C#代码

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

完美工作!!!

答案 1 :(得分:6)

我找到了解决方案:

replacementKey = "*|VERIFICATION_URL|*";
substitutionValues = new List<string> { VERIFICATION_URL };

myMessage.AddSubstitution(replacementKey, substitutionValues);

答案 2 :(得分:3)

我使用了以下方法。请注意,您必须提供mail.Textmail.Html值 - 我使用空字符串和<p></p>标记,如示例中所示。您的SendGrid模板仍然必须包含默认的<%body%><%subject%>令牌,但它们将替换为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");

答案 3 :(得分:3)

经过大量的RND。我的下面代码工作正常&amp;也经过了测试。

            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标头的Separate方法

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-&amp;对于文本替换,您需要使用{{UserKeyForReplace}}