1

我有一个问题:是否可以在不让用户单击 Outlook 中的自动下载的情况下以某种方式在邮件中嵌入图像?

我写了简单的 C# 代码:

string message = "<p><img src='test1.jpg' />";
SendEmail( "to@test.com", "from@test.com", "Subject", message );

在我的 Outlook 中,图像是隐藏的,我必须单击自动下载图像。

我也尝试将图像源编写为 base64 代码

string message = "<p><img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAR8AAAA8CA...' />";
SendEmail( "to@test.com", "from@test.com", "Subject", message );

但它不起作用。

4

2 回答 2

1

可以做到——您必须将图像作为链接资源嵌入。以下代码将 img 标签替换为等效标签,在服务器端下载图像并将它们作为链接资源附加到电子邮件。

public void Email(string htmlBody, string emailSubject) {
  var mailMessage = new MailMessage("from@company.com", "to@company.com");
  mailMessage.IsBodyHtml = true;
  mailMessage.SubjectEncoding = Encoding.UTF8;
  mailMessage.BodyEncoding = Encoding.UTF8;
  mailMessage.Body = htmlBody;
  mailMessage.Subject = emailSubject;
  // embedd images
  var imageUrls = new List<EmailImage>();
  var regexImg = new Regex(@"<img[^>]+>", RegexOptions.IgnoreCase);
  var regexSrc = new Regex(@"src=[""](?<url>[^""]+)[""]", RegexOptions.IgnoreCase);
  mailMessage.Body = regexImg.Replace(mailMessage.Body, (matchImg) => {
    var value = regexSrc.Replace(matchImg.Value, (matchSrc) => {
      string url = matchSrc.Groups["url"].Value;
      var image = imageUrls.Where(i => string.Compare(i.Url, url, StringComparison.OrdinalIgnoreCase) == 0).FirstOrDefault();
      if (image == null) {
        image = new EmailImage { Url = url, MailID = Convert.ToString(imageUrls.Count) };
        imageUrls.Add(image);
      }
      return string.Format(@"src=""cid:{0}""", image.MailID);
    });
    return value;
  });

  if (imageUrls.Count > 0) {
    var htmlView = AlternateView.CreateAlternateViewFromString(mailMessage.Body, null, "text/html");
    for (int i = 0; i < imageUrls.Count; i++) {
      var request = WebRequest.Create(imageUrls[i].Url);
      var response = (HttpWebResponse)request.GetResponse();
      var stream = response.GetResponseStream();
      var memoryStream = new MemoryStream((int)response.ContentLength);
      CopyStream(stream, memoryStream);
      memoryStream.Seek(0, SeekOrigin.Begin);
      var imageLink = new LinkedResource(memoryStream, GetContentType(response.ContentType, imageUrls[i].Url));
      imageLink.ContentId = imageUrls[i].MailID;
      imageLink.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
      htmlView.LinkedResources.Add(imageLink);
    }
    mailMessage.AlternateViews.Add(htmlView);
  }

  SmtpClient.Send(mailMessage);
}

支持方法/类:

private void CopyStream(Stream input, Stream output) {
  byte[] buffer = new byte[32768];
  int read;
  while ((read = input.Read(buffer, 0, buffer.Length)) > 0) {
    output.Write(buffer, 0, read);
  }
}

private string GetContentType(string serverContentType, string imageUrl) {
  if (string.IsNullOrEmpty(imageUrl))
    throw new ArgumentNullException("imageUrl");

  ImageMimeType mimeType;
  if (!string.IsNullOrEmpty(serverContentType)) {
    serverContentType = serverContentType.ToLowerInvariant();
    mimeType = ImageMimeType.MimeTypes.Where(m => m.MimeType == serverContentType).FirstOrDefault();
    if (mimeType != null) {
      return mimeType.MimeType;
    }
  }

  string extension = Path.GetExtension(imageUrl).ToLowerInvariant();
  mimeType = ImageMimeType.MimeTypes.Where(m => m.FileExtension == extension).FirstOrDefault();
  if (mimeType != null) {
    return mimeType.MimeType;
  }
  return "application/octet-stream";
}


private class EmailImage {
  public string Url { get; set; }
  public string MailID { get; set; }
}


private class ImageMimeType {
  public string FileExtension { get; private set; }
  public string MimeType { get; private set; }
  public static List<ImageMimeType> MimeTypes = new List<ImageMimeType> {
    new ImageMimeType { FileExtension = ".png", MimeType = "image/png"},
    new ImageMimeType { FileExtension = ".jpe", MimeType = "image/jpeg" },
    new ImageMimeType { FileExtension = ".jpeg", MimeType = "image/jpeg" },
    new ImageMimeType { FileExtension = ".jpg", MimeType = "image/jpeg" },
    new ImageMimeType { FileExtension = ".gif", MimeType = "image/gif" },
    new ImageMimeType { FileExtension = ".bmp", MimeType = "image/bmp" }
  };
}
于 2013-06-19T08:53:30.887 回答
0

如果图像很简单(即颜色不多,几何形状简单),您可以将其转换为 HTML 表格,然后将其嵌入 HTML 电子邮件中。您可以使用开源工具进行转换。

于 2013-06-19T12:52:50.063 回答