Sendgrid V3 Example with Attachment

1

I need an example code to send email with attachment using sendgrid Web API v3.

using (var client = new HttpClient())
{
  client.BaseAddress = new Uri("https://api.sendgrid.com/");
  client.DefaultRequestHeaders.Accept.Clear();
  client.DefaultRequestHeaders.Accept.Add(
     new MediaTypeWithQualityHeaderValue("application/json"));
  client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(
Encoding.ASCII.GetBytes(String.Format("{0}:{1}", 
  credentials.UserName, credentials.Password))));

  var data = new NewTemplate()
  {
    html_content = "<%body%>",
    name = template.name + "_" + template.Versions.Count(),
    plain_content = "<%body%>",
    subject = "<%subject%>"
  };

  var content = JsonConvert.SerializeObject(data) as string;
  var response = await client.PostAsync(
      String.Format("v3/templates/{0}/versions", template.id), 
      new StringContent(content,Encoding.UTF8,"application/json"));
}

In the above code, authentication is done via UserName and Password. I need to change to authenticate via APIKey.

    
asked by anonymous 19.07.2016 / 19:28

1 answer

1

I was able to use sendgrid

1) PM> Install-Package SendGrid ;

2) I've added the following code:

using System;
using System.Web.Script.Serialization;
using SendGrid;
using SendGrid.Helpers.Mail;


private static void SendEmail()
        {
        String apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY", EnvironmentVariableTarget.User);
        dynamic sg = new SendGridAPIClient(apiKey);

        Email email = new Email();
        email.Name = "Example User";
        email.Address = "[email protected]";
        mail.From = email;

        String subject = "Hello World!!!!";

        Personalization personalization = new Personalization();
        email = new Email();
        email.Name = "Example User";
        email.Address = "[email protected]";
        personalization.AddTo(email);


        content = new Content();
        content.Type = "text/html";
        content.Value = "<html><body>HTML content</body></html>";
        mail.AddContent(content);


         Attachment attachment = new Attachment();
        attachment.Content = "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12";
        attachment.Type = "application/pdf";
        attachment.Filename = "balance_001.pdf";
        attachment.Disposition = "attachment";
        attachment.ContentId = "Balance Sheet";
        mail.AddAttachment(attachment);

        dynamic response = sg.client.mail.send.post(requestBody: mail.Get());

        Console.WriteLine(response.StatusCode);
        Console.WriteLine(response.Body.ReadAsStringAsync().Result);
        Console.WriteLine(response.Headers.ToString());
    }
}
    
19.07.2016 / 22:15