Sam
Sam

Reputation: 30388

SendGrid API for C#

I'm looking at the SendGrid API for C# and the task is to send a single email to multiple recipients.

I'm following this example but I want to keep working with objects -- not JSON. https://github.com/sendgrid/sendgrid-csharp/blob/master/USE_CASES.md

How do I add multiple recipient emails? Looks like it's under Personalizations but their API is not giving me much help in adding multiple recipients.

Mail mail = new Mail();
mail.From = new Email("[email protected]");
mail.Subject = "Some Subject";

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

If I wanted to email a single email address, I can simply do this:

Email from = new Email("[email protected]");
Email to = new Email("[email protected]");
string subject = "Some subject";
Content content = new Content("text/plain", "Hello World!");
Mail mail = new Mail(from, subject, to, content);

Upvotes: 5

Views: 24733

Answers (6)

John Trenwith
John Trenwith

Reputation: 763

The SendGrid v3 API supports sending a single email to multiple recipients. Here's an example with the .NET NuGet package:

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

where the "sender" parameter is of type "SendGrid.Helpers.Mail.EmailAddress" and the "recipients" parameter is a List of type "SendGrid.Helpers.Mail.EmailAddress".

See this SO question for some more code examples.

Upvotes: 1

Send mail with attachment:

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;
            }
        }

Upvotes: 0

Jeff Blumenthal
Jeff Blumenthal

Reputation: 472

I was looking for an ASP.Net Web Forms solution. I started with the SendGrid nuGet package.

  1. Then go to https://github.com/sendgrid/sendgrid-csharp
  2. download the zip or git clone
  3. Open up the solution in the ExampleNet45ASPNetProject it has some good hints in there.

But here is some code I did. First the helper class then the OnClick event:

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("[email protected]", "Bill Jo Bob Tex Jr.", "[email protected]", "[email protected]", "subject", body);
}

Upvotes: 0

Eldho
Eldho

Reputation: 8273

 // 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("[email protected]");
myMessage.AddTo("[email protected]");
myMessage.AddTo("[email protected]");
myMessage.From = new MailAddress("[email protected]", "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);

If you see the AddTo() method is adding the emails to a collection.AddTo()

SendGrid reference

Upvotes: 0

Ruan Cowley
Ruan Cowley

Reputation: 46

Here is some code I wrote to test sending to multiple recipients. The code below adds two emails to a single request. I tested it and it worked perfectly.

You just need to declare a new instance of the Personalization object as a List. Populate your individual Personalization objects with the required details for the recipient or recipients of the email. Add to your Personalization List you have declared and then you will be sorted.

See below and let me know if this helps. My code is pretty self explanatory. I also enabled the tracking for when the recipients open the email. The below should put you in the right direction and you will be able to send multiple emails by sending a single request to the API. :)

Any questions let me know. Have fun! :)

    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("[email protected]", "Recipient 1");
            emails.Add(email);

            email = new Email("[email protected]", "Recipient 2");
            emails.Add(email);

            email = new Email("[email protected]", "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("[email protected]", "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();
        }
    }

Upvotes: 3

Nikolay Kostov
Nikolay Kostov

Reputation: 16963

I am using my own custom implementation of the SendGrid API since it's C# API does not have support for .NET Core.

Here are the API models and the implementation. You will need to reference JSON.NET in order for the JSON parsing and serializing to work properly.

SendGridContent

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; }
}

SendGridPersonalization

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; }
}

My service interface

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

And the implementation

// 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);
        }
    }
}

Upvotes: 0

Related Questions