Robbie Mills
Robbie Mills

Reputation: 2945

Can't send attachment with sendgrid api

I have a byte[] which is a downloaded pdf file in my ASP.NET Core 2.1 app.

I'm trying to attach this as an attachment to a sendgrid email message.

public async Task SendEmail(byte[] Attachment = null)
{
    var client = new SendGridClient(apiKey);

    var msg = new SendGridMessage();

    // I also set the To, Subject, body etc etc

    msg.AddAttachment("test.pdf",Convert.ToBase64String(Attachment) ,"application/pdf","inline");
    var response = await client.SendEmailAsync(msg);

}

I get a 'BadReqest' status code. If I remove the AddAttachment line then the message is accepted.

What am I doing wrong?

Upvotes: 1

Views: 882

Answers (1)

Mohsin Mehmood
Mohsin Mehmood

Reputation: 4236

Try something like this:

 using (var stream = new MemoryStream(Attachment))
    {
        msg.AddAttachment("test.pdf", stream);
        var response = await client.SendEmailAsync(msg);
    }

Upvotes: 2

Related Questions