【问题标题】:SendGrid API for C#C# 的 SendGrid API
【发布时间】:2017-05-14 07:05:59
【问题描述】:

我正在查看用于 C# 的 SendGrid API,任务是向多个收件人发送一封电子邮件。

我正在关注这个示例,但我想继续使用对象——而不是 JSON。 https://github.com/sendgrid/sendgrid-csharp/blob/master/USE_CASES.md

如何添加多个收件人电子邮件?看起来它在 Personalizations 下,但他们的 API 在添加多个收件人方面没有给我太多帮助。

Mail mail = new Mail();
mail.From = new Email("me@me.com");
mail.Subject = "Some Subject";

// How do I add multiple emails to To field? 

如果我想通过电子邮件发送单个电子邮件地址,我可以这样做:

Email from = new Email("me@me.com");
Email to = new Email("joe@joe.com");
string subject = "Some subject";
Content content = new Content("text/plain", "Hello World!");
Mail mail = new Mail(from, subject, to, content);

【问题讨论】:

  • 我认为这不是 API 所期望的。我可以只使用 JSON,但我更喜欢处理对象,因为我在 C# 中。
  • Email to = new Email("joe@joe.com;linda@linda.com;another@me.com");
  • 我不知道 SendGrid,但这是通常的方式。
  • 我明白你在说什么,但这是一项付费服务​​,所以他们只显示一个收件人示例可能是有原因的。他们可能希望我们改为发送多封电子邮件。在 GitHub 上,他们正在讨论一个问题:github.com/sendgrid/sendgrid-csharp/issues/333
  • 我使用 SendGrid 通过 web.config 设置它,只使用 email.To.Add() 或 email.Bcc.Add() 就像从 C# 发送电子邮件的标准方式一样>

标签: c# sendgrid


【解决方案1】:

SendGrid v3 API 支持向多个收件人发送一封电子邮件。这是 .NET NuGet package 的示例:

var message = MailHelper.CreateSingleEmailToMultipleRecipients(sender, recipients, subject, plainTextContent, htmlContent);

其中“sender”参数是“SendGrid.Helpers.Mail.EmailAddress”类型,“recipients”参数是“SendGrid.Helpers.Mail.EmailAddress”类型列表。

更多代码示例请参见this SO question

【讨论】:

    【解决方案2】:

    发送带有附件的邮件:

    public static async Task<Tuple<string, string, string>> SendEmailUsingSendGrid(string filePath)
            {
                try
                {
                    var apiKey = EmailComponents.apiKey;
                    var client = new SendGridClient(apiKey);
                    var messageEmail = new SendGridMessage()
                    {
                        From = new EmailAddress(EmailComponents.fromEmail, EmailComponents.fromEmaliUserName),
                        Subject = EmailComponents.Subject,
                        PlainTextContent = EmailComponents.plainTextContent,
                        HtmlContent = EmailComponents.htmlContent
                    };
                    messageEmail.AddTo(new EmailAddress(EmailComponents.emailTo, EmailComponents.emailToUserName));
                    var bytes = File.ReadAllBytes(filePath);
                    var file = Convert.ToBase64String(bytes);
                    messageEmail.AddAttachment("Voucher Details Report.pdf", file);
    
    
                    var response = await client.SendEmailAsync(messageEmail);
    
                    return new Tuple<string, string, string>(response.StatusCode.ToString(), 
                        response.Headers.ToString(), 
                        response.Body.ToString());
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    

    【讨论】:

      【解决方案3】:

      我一直在寻找 ASP.Net Web 表单解决方案。我从 SendGrid nuGet 包开始。

      1. 那就去https://github.com/sendgrid/sendgrid-csharp
      2. 下载 zip 或 git clone
      3. 在 ExampleNet45ASPNetProject 中打开解决方案,其中有一些很好的提示。

      但这是我做的一些代码。 首先是助手类,然后是 OnClick 事件:

      using SendGrid;
      using SendGrid.Helpers.Mail;
      using System.Collections.Generic;
      using System.Threading.Tasks;
      
      namespace Somenamespace.Utils
      {
          public class SMTPUtils
          {
      
              public async void SendEmail(string address, string toName, string fromName, string fromAddress, string subject, string body)
              {
                  SendGridMessage msg = new SendGridMessage();
                  msg.SetFrom(new EmailAddress(fromAddress, fromName));
                  var recipients = new List<EmailAddress>
                  {
                      new EmailAddress(address, toName),
                  };
                  msg.AddTos(recipients);
                  msg.SetSubject(subject);
                  msg.AddContent(MimeType.Text, body);
      
                  await Execute(msg);
              }
      
              private async Task Execute(SendGridMessage msg)
              {
                  var client = new SendGridClient(yourAPIKey);
                  var response = await client.SendEmailAsync(msg);
              }
          }
      }
      
      protected void BtnSubmit_Click(object sender, EventArgs e)
      {
          string body = "some message body";
      
          SMTPUtils smtp = new SMTPUtils();
          smtp.SendEmail("someone@somewhere.com", "Bill Jo Bob Tex Jr.", "fromsomeone@somewhere.com", "noreply@example.com", "subject", body);
      }
      

      【讨论】:

        【解决方案4】:
         // using SendGrid's C# Library - https://github.com/sendgrid/sendgrid-csharp
        using System.Net.Http;
        using System.Net.Mail;
        
        var myMessage = new SendGrid.SendGridMessage();
        myMessage.AddTo("test@sendgrid.com");
        myMessage.AddTo("test@sendgrid.com");
        myMessage.AddTo("test@sendgrid.com");
        myMessage.From = new MailAddress("you@youremail.com", "First Last");
        myMessage.Subject = "Sending with SendGrid is Fun";
        myMessage.Text = "and easy to do anywhere, even with C#";
        
        var transportWeb = new SendGrid.Web("SENDGRID_APIKEY");
        transportWeb.DeliverAsync(myMessage);
        

        如果您看到 AddTo() 方法正在将电子邮件添加到集合中。AddTo()

        SendGrid reference

        【讨论】:

          【解决方案5】:

          这是我编写的一些代码,用于测试向多个收件人发送。下面的代码将两封电子邮件添加到一个请求中。我对其进行了测试,并且效果很好。

          您只需要将 Personalization 对象的新实例声明为 List。 使用电子邮件收件人所需的详细信息填充您的个人个性化对象。添加到您已声明的个性化列表中,然后您将被排序。

          请参阅下文,如果这有帮助,请告诉我。我的代码很容易解释。我还启用了收件人打开电子邮件的跟踪功能。下面的内容应该会让您朝着正确的方向前进,您将能够通过向 API 发送单个请求来发送多封电子邮件。 :)

          如有任何问题,请告诉我。玩得开心! :)

              static void Main(string[] args)
              {
                  Execute().Wait();           
              }
          
          
              static async Task Execute()
              {
          
                  try
                  {
                      string apiKey = "apikey value";
                      dynamic sg = new SendGridAPIClient(apiKey);
          
                      //Declare Mail object
                      Mail mail = new Mail();               
          
                      //Declare List as Personalization object type 
                      List<Personalization> personal = new List<Personalization>();
          
                      //Declare Personalization object to add to List above
                      Personalization emailItem = new Personalization();
          
                      emailItem.Subject = "Hi there";
          
                      //Declare List as Email type 
                      List<Email> emails = new List<Email>();
          
                       //Declare Email object to add to List above
                      Email email = new Email();
          
          
                      email = new Email("email1@example.com", "Recipient 1");
                      emails.Add(email);
          
                      email = new Email("email2@example.com", "Recipient 2");
                      emails.Add(email);
          
                      email = new Email("email3@example.com", "Recipient 3");
                      emails.Add(email);
          
                      emailItem.Tos = emails;
                      personal.Add(emailItem);
          
          
                      mail.Personalization = personal;
          
                      List<Content> contents = new List<Content>();
          
                      Content content = new Content("text/plain", "Test contents");
                      contents.Add(content);
          
                      Email from = new Email("no-reply@test.com", "Test App");
                      string subject = "Testing Sending with SendGrid is Fun";
                      mail.Subject = subject;
                      mail.From = from;
          
                      mail.Contents = contents;
          
                    dynamic response = await sg.client.mail.send.post(requestBody: mail.Get());
          
                      Console.WriteLine(response.StatusCode);
                      Console.WriteLine(response.Body.ReadAsStringAsync().Result);
                      Console.WriteLine(response.Headers.ToString());
                      Console.Read();
                  }
                  catch (Exception ex)
                  {
                      Console.WriteLine(ex.ToString());
                      Console.Read();
                  }
              }
          

          【讨论】:

          • 感谢您提供的代码,它很有帮助,但如果我没记错的话,此代码将通过一个 API 调用发送 2 封电子邮件,对吗?我实际上想将相同的电子邮件发送给多个收件人——有点像我们在普通电子邮件中所做的。例如,在您的代码中,我看到您正在自定义主题行。我读错了吗?
          • 正是你所说的。我已经修改了上面的答案。我现在将多封电子邮件添加到一个个性化对象。我的代码再一次直截了当。如果您不明白,请告诉我。
          • 如果您想从 app.config 中检索电子邮件列表怎么办?而不是硬编码电子邮件,以便可以即时更改。
          【解决方案6】:

          我正在使用我自己的 SendGrid API 自定义实现,因为它的 C# API 不支持 .NET Core。

          这里是 API 模型和实现。您需要参考 JSON.NET 才能使 JSON 解析和序列化正常工作。

          发送网格内容

          public class SendGridContent
          {
              public SendGridContent()
              {
              }
          
              public SendGridContent(string type, string content)
              {
                  this.Type = type;
                  this.Value = content;
              }
          
              [JsonProperty("type")]
              public string Type { get; set; }
          
              [JsonProperty("value")]
              public string Value { get; set; }
          }
          

          SendGridEmail

          public class SendGridEmail
          {
              public SendGridEmail()
              {
              }
          
              public SendGridEmail(string email, string name = null)
              {
                  this.Email = email;
                  this.Name = name;
              }
          
              [JsonProperty("email")]
              public string Email { get; set; }
          
              [JsonProperty("name")]
              public string Name { get; set; }
          }
          

          SendGridMessage

          public class SendGridMessage
          {
              public const string TypeText = "text";
              public const string TypeHtml = "text/html";
          
              public SendGridMessage()
              {
              }
          
              public SendGridMessage(SendGridEmail to, string subject, SendGridEmail from, string message, IEnumerable<SendGridEmail> bcc = null, string type = TypeHtml)
              {
                  this.Personalizations = new List<SendGridPersonalization>
                  {
                      new SendGridPersonalization
                      {
                          To = new List<SendGridEmail> { to },
                          Bcc = bcc,
                          Subject = subject
                      }
                  };
                  this.From = from;
                  this.Content = new List<SendGridContent> { new SendGridContent(type, message) };
              }
          
              [JsonProperty("personalizations")]
              public List<SendGridPersonalization> Personalizations { get; set; }
          
              [JsonProperty("from")]
              public SendGridEmail From { get; set; }
          
              [JsonProperty("content")]
              public List<SendGridContent> Content { get; set; }
          }
          

          SendGrid个性化

          public class SendGridPersonalization
          {
              [JsonProperty("to")]
              public List<SendGridEmail> To { get; set; }
          
              [JsonProperty("bcc")]
              public IEnumerable<SendGridEmail> Bcc { get; set; }
          
              [JsonProperty("subject", NullValueHandling = NullValueHandling.Ignore)]
              public string Subject { get; set; }
          }
          

          我的服务界面

          public interface IEmailSender
          {
              Task Send(
                  string fromAddress,
                  string fromName,
                  string to,
                  string subject,
                  string message,
                  IEnumerable<string> bcc = null);
          }
          

          以及实施

          // Documentation: https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html
          public class SendGridEmailSender : IEmailSender
          {
              private readonly HttpClient httpClient;
          
              public SendGridEmailSender(string apiKey)
              {
                  this.httpClient = new HttpClient();
                  this.httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
                  this.httpClient.BaseAddress = new Uri("https://api.sendgrid.com/v3/");
              }
          
              // TODO: Delete custom code and use their library once the SendGrid library starts to support .NET Core
              // Implemented using custom SendGrid API usage implementation due to lack of .NET Core support for their library
              public async Task Send(
                  string fromAddress,
                  string fromName,
                  string to,
                  string subject,
                  string message,
                  IEnumerable<string> bcc = null)
              {
                  var bccEmails = bcc?.Select(c => new SendGridEmail { Email = c, Name = fromName });
                  var msg = new SendGridMessage(
                      new SendGridEmail(to),
                      subject,
                      new SendGridEmail(fromAddress, fromName),
                      message,
                      bccEmails);
                  try
                  {
                      var json = JsonConvert.SerializeObject(msg);
                      var response = await this.httpClient.PostAsync(
                          "mail/send",
                          new StringContent(json, Encoding.UTF8, "application/json"));
          
                      if (!response.IsSuccessStatusCode)
                      {
                          // See if we can read the response for more information, then log the error
                          var errorJson = await response.Content.ReadAsStringAsync();
                          throw new Exception(
                              $"SendGrid indicated failure! Code: {response.StatusCode}, reason: {errorJson}");
                      }
                  }
                  catch (Exception)
                  {
                      // TODO: await this.logger.LogExceptionAsync(ex);
                  }
              }
          }
          

          【讨论】:

          • 感谢您的代码。因此,您正在使用 C# 对象,但最终,您将 JSON 对象发送到 SendGrid API。另外,我认为在您的代码中,您将消息发送给单个收件人,但我认为诀窍是使用 List - 与@RuanCowley 在下面的回答中所建议的相同。
          • 嘿@nikolay 您是否有任何SendGrid 的工作示例以及您提到的上述实体。我喜欢您的解决方案,并且正在寻找完全相同的解决方案。
          • @tt0206 是的,请检查我的 ASP.NET Core 模板与此处集成的 SendGrid:github.com/NikolayIT/ASP.NET-MVC-Template/blob/master/…
          猜你喜欢
          • 1970-01-01
          • 2012-09-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-07-24
          • 1970-01-01
          • 2023-04-10
          • 1970-01-01
          相关资源
          最近更新 更多