jeffkenn jeffkenn - 16 days ago 8
C# Question

Attaching to sendgrid api not working when using sendgrid mail helper

I have looked through the questions i can find on here about attaching a file to a sendgrid email but none seem to have the issue I am.

My question is is this. How do you send an email with an attachment in sendgrid using the api?

dynamic sg = new SendGridAPIClient(apiKey);
var from = new SendGrid.Helpers.Mail.Email("jkennedy@domain.com");
var subject = "Hello World from the SendGrid C# Library!";
var to = new SendGrid.Helpers.Mail.Email(toAddress);
var content = new Content("multipart/form-data", "Textual content");
var attachment = new Attachment {Filename = attachmentPath };
var mail = new Mail(from, subject, to, content);

var ret = mail.Get();

mail.AddAttachment(attachment);


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


If i put the mail.attachment after the get the mail sends but there is no attachment. If i put the addattachment line before the get i get a "bad request" message.

I have yet to find an example of exactly how to do this.

Also, the path to the file is c:\tblaccudatacounts.csv

Answer

I figure it out. I was using a helper written by a third party. I went with what with SendGrid actually suggested. See code below that is now working.

var myMessage = new SendGridMessage {From = new MailAddress("info@email.com")};
        myMessage.AddTo("Jeff Kennedy <info@info.com>");
        myMessage.Subject = "test email";
        myMessage.Html = "<p>See Attachedment for Lead</p>";
        myMessage.Text = "Hello World plain text!";
        myMessage.AddAttachment("C:\\tblaccudatacounts.csv");
        var apiKey = "apikey given by sendgrid";
        var transportWeb = new Web(apiKey);
        await transportWeb.DeliverAsync(myMessage);
Comments