jeffkenn jeffkenn - 2 months ago 34
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("");
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();


dynamic response = await 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


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("")};
        myMessage.AddTo("Jeff Kennedy <>");
        myMessage.Subject = "test email";
        myMessage.Html = "<p>See Attachedment for Lead</p>";
        myMessage.Text = "Hello World plain text!";
        var apiKey = "apikey given by sendgrid";
        var transportWeb = new Web(apiKey);
        await transportWeb.DeliverAsync(myMessage);