SendGrid图片电子邮件

时间:2018-01-18 07:21:56

标签: c# asp.net .net sendgrid sendgrid-api-v3

我正在尝试使用以下代码通过Sendgrid发送电子邮件。电子邮件中有一张我想发送的图片。

        var client = new SendGridClient("MYAPIKEY");
        var from = new EmailAddress("from@from.com");
        var subject = "test";
        var to = new EmailAddress("to@to.com");
        var plainTextContent = "";
        Image s = CreateBitmapImage("Hi");
        ImageConverter converter = new ImageConverter();
        var imageBytes = (byte[])converter.ConvertTo(s, typeof(byte[]));
        var b64String = Convert.ToBase64String(imageBytes);
        var dataUrl = "data:image/jpg;base64," + b64String;
        var htmlContent = "<img src='" + dataUrl + "' />";
        var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);

        var response = client.SendEmailAsync(msg).Result;

以下是我在发送图片后在gmail中看到的内容。

Result in gmail

我提到了sendgrid blogpost,用于通过base64嵌入图像。如果我在某处做错了,请建议。

1 个答案:

答案 0 :(得分:0)

你检查一下你是否设定了它?

MailMessage msg = new MailMessage();  
msg.IsBodyHtml = true;   
msg.BodyEncoding = Encoding.GetEncoding("utf-8");   

如果设置,则尝试

  var dataUrl = "";
  using (System.Drawing.Image s = CreateBitmapImage("Hi"))
  {
    ImageConverter converter = new ImageConverter();
    var imageBytes = (byte[])converter.ConvertTo(s, typeof(byte[]));
    var b64String = Convert.ToBase64String(imageBytes);
    dataUrl = "data:image/jpg;base64," + b64String;
  }
  var htmlContent = "<img src=\"" + dataUrl + "\" />";