1

Estou precisando de um exemplo de código para envio de email com anexo utilizando 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"));
}

No código acima, a autenticação é feita via UserName e Password. Eu preciso alterar para fazer a autenticação via APIKey.

3

1 Resposta 1

1

Consegui usando o sendgrid

1) PM> Install-Package SendGrid;

2) Adicionei o seguinte código :

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

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .