简体   繁体   English

使用ASP.NET MVC C#发送电子邮件时,将图像嵌入到Outlook 2010中

[英]Embed an image in Outlook 2010 when send email with ASP.NET MVC C#

I have a question: it is possible to embed somehow an image in mail message without let user to click automatic download in Outlook ? 我有一个问题:是否可以在邮件中嵌入图像而不用让用户单击Outlook中的自动下载?

I wrote simple C# code: 我写了简单的C#代码:

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

In my Outlook, the image is hidden and I have to click on Automatic download images. 在我的Outlook中,该图像是隐藏的,我必须单击“自动下载图像”。

I tried also to write image source as base64 code 我也尝试将图像源编写为base64代码

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

but it doesn't work. 但这不起作用。

It can be done - you have to embed images as linked resource. 可以做到的-您必须将图像嵌入为链接资源。 Following code replaces img tags with their equivalents, downloads images on server side and attaches them as linked resource to email. 以下代码将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);
}

Support methods/classes: 支持方法/类:

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" }
  };
}

If the image is simple (ie not many colors, simple geometry) you can convert it into an HTML table, and then embed it in an HTML e-mail. 如果图像很简单(即颜色不多,几何形状不多),则可以将其转换为HTML表,然后将其嵌入HTML电子邮件中。 You can use this open source tool to do the conversion. 您可以使用开源工具进行转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM