如何使用SendGrid将文件作为附件附加到电子邮件中?

时间:2020-01-13 09:16:13

标签: c# email sendgrid email-attachments sendgrid-api-v3

我想使用SendGrid和C#将文件作为附件附加-我有下面的代码可以运行,但是返回的response.StatusCode

BadResponse

如何更改此代码,以便附加文件并成功发送电子邮件?

var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var listAtta = new List<FileAttachment>();
emailProducts.Select(o => o.tp).ToList().ForEach(o =>
{
    string file = o.ProductPdf;
    var fileBytes = FileToByteArray(o.ProductPdf);
    if (fileBytes != null && fileBytes.Count() > 0)
    {
        listAtta.Add(new FileAttachment
        {
            FileData = fileBytes,
            FileName = o.ProductPdf
        }); ;
    }
    msg.AddAttachment(o.ProductPdf, fileBytes.ToString());
});

var response = await client.SendEmailAsync(msg);
var success = response.StatusCode;

1 个答案:

答案 0 :(得分:0)

您需要对它进行base64编码 msg.AddAttachment(o.ProductPdf,Convert.ToBase64String(bytes))