Sendgrid取消订阅偏好

时间:2016-07-21 02:56:52

标签: c# smtp sendgrid

我正在使用Sendgrid并尝试使用C#语言发送这些电子邮件。 所以,我正在做的是在我的应用程序中配置SMTP和API密钥,然后繁荣,发送电子邮件。

问题是,如何在我的X-SMTPAPI标头中插入取消订阅首选项组? 仅供参考,取消订阅首选项是您可以选择要取消订阅的组而非全局取消订阅的地方。

我已经检查了这些链接:

我还在他们的github上检查了库C#。 但这些都没有让我清楚。

我对JSON,GET,REQUEST,RESPONSE等完全视而不见。

这是我的C#代码

        public void Main()
                {
                    string sSubject = Dts.Variables["vSubject"].Value.ToString();
                    string sBody = Dts.Variables["vBodyMessage"].Value.ToString();

                    int iPriority = 2;



                    if (SendMail(sSubject, sBody, iPriority))
                    {
                        Dts.TaskResult = (int)ScriptResults.Success;
                    }
                    else
                    {
                        //Fails the Task
                        Dts.TaskResult = (int)ScriptResults.Failure;
                    }
                }

//THIS IS THE HEADER X-SMTPAPI, I DUNNO HOW TO USE IT :(
//I WANNA ADD MY GROUPS HERE
    private static string XsmtpapiHeaderAsJson()
            {
                var header = new Header();
                header.SetAsmGroupId(777);

                //var uniqueArgs = new string[] { "Small", "Medium", "Large" };
                //{

                //      "asm_groups_to_display": [1, 2, 3]

                //};
                //header.AddUniqueArgs({ "asm_groups_to_display": ['1', '2', '3']});

                //var subs = new List<String> { "私はラーメンが大好き" };
                //header.AddSubstitution("%tag%", subs);

                //dynamic stuff = json

                return header.JsonString();
            }

    public bool SendMail(string sSubject, string sMessage, int iPriority)
            {
                string xmstpapiJson = XsmtpapiHeaderAsJson();

                try
                {
                    string sEmailServer = Dts.Variables["sServer"].Value.ToString();
                    string sEmailPort = Dts.Variables["sPort"].Value.ToString();
                    string sEmailUser = Dts.Variables["sUser"].Value.ToString();
                    string sEmailPassword = Dts.Variables["sPassword"].Value.ToString();
                    string sEmailSendTo = Dts.Variables["sSendTo"].Value.ToString();
                    string sEmailSendToName = Dts.Variables["sSendToName"].Value.ToString();
                    //string sEmailSendCC = Dts.Variables["sSendCC"].Value.ToString();
                    string sEmailSendFrom = Dts.Variables["sFrom"].Value.ToString();
                    string sEmailSendFromName = Dts.Variables["sFromName"].Value.ToString();

                    SmtpClient smtpClient = new SmtpClient();
                    MailMessage message = new MailMessage();

                    MailAddress fromAddress = new MailAddress(sEmailSendFrom, sEmailSendFromName);

                    //You can have multiple emails separated by ;
                    string[] sEmailTo = Regex.Split(sEmailSendTo, ";");
                    //string[] sEmailCC = Regex.Split(sEmailSendCC, ";");
                    int sEmailServerSMTP = int.Parse(sEmailPort);

                    smtpClient.Host = sEmailServer;
                    smtpClient.Port = sEmailServerSMTP;

                    System.Net.NetworkCredential myCredentials =
                       new System.Net.NetworkCredential(sEmailUser, sEmailPassword);
                    smtpClient.Credentials = myCredentials;

                    message.From = fromAddress;

                    //MailAddress toAddress = new MailAddress(sEmailSendTo, sEmailSendToName);
                    //message.To.Add(toAddress);

                    if (sEmailTo != null)
                    {
                        for (int i = 0; i < sEmailTo.Length; ++i)
                        {
                            if (sEmailTo[i] != null && sEmailTo[i] != "")
                            {
                                MailAddress toAddress = new MailAddress(sEmailTo[i], sEmailSendToName);
                                message.To.Add(toAddress);


                            }
                        }
                    }

                    switch (iPriority)
                    {
                        case 1:
                            message.Priority = MailPriority.High;
                            break;
                        case 3:
                            message.Priority = MailPriority.Low;
                            break;
                        default:
                            message.Priority = MailPriority.Normal;
                            break;
                    }


                    //message.Headers.Add("X-SMTPAPI", xmstpapiJson);

                    //smtpClient.SendCompleted += SendCompletedCallback;
                    //const string state = "test1";

                    message.Subject = sSubject;
                    message.IsBodyHtml = true;
                    message.Body = sMessage;

                    //smtpClient.SendAsync(message, state);
                    smtpClient.Send(message);
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }

1 个答案:

答案 0 :(得分:4)

我明白你的意思,smtpapi-csharp项目根本就没有实现这个概念..但这是一个微不足道的事情。 (这个实用程序项目的值开头有问题。)

这里唯一重要的一点就是注释掉了。

//message.Headers.Add("X-SMTPAPI", xmstpapiJson);

应该是,

message.Headers.Add("X-SMTPAPI", @"{ ""asm_group_id"" : 777, ""asm_groups_to_display"" : [777] }"); 

基本上,您只是将json分配给此标头。 Documentation提供此示例

{
  "asm_groups_to_display": [1, 2, 3]
}

[1, 2, 3]是一个整数数组,与GroupIds相关。

可替换地,

fork the git并将以下内容添加到Header.cs

/// <summary>
///     This sets which groups to display on the Manage Preferences page of an email.  You can find further documentation about ASM here:
///     https://sendgrid.com/docs/API_Reference/SMTP_API/suppressions.html
/// </summary>
/// <param name="ids">ASM groups to display applied to the message</param>
public void SetAsmGroupsToDisplay(params int[] ids)
{
    _settings.AddArray(new List<string> {"asm_groups_to_display"}, ids);
}

构建并更新csproj引用以使用分叉项目。

然后,像这样呼叫SetAsmGroupsToDisplay

private static string XsmtpapiHeaderAsJson()
{
    var header = new Header();
    header.SetAsmGroupId(777);
    header.SetAsmGroupsToDisplay(777); // SetAsmGroupsToDisplay(new int[] {777}) works too
    return header.JsonString();
}

,当然,使用方法:

message.Headers.Add("X-SMTPAPI", XsmtpapiHeaderAsJson());

...当你开始工作时,不要忘记添加一个Pull Request。