Snake Eyes
Snake Eyes

Reputation: 16764

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 ?

I wrote simple C# code:

string message = "<p><img src='test1.jpg' />";
SendEmail( "[email protected]", "[email protected]", "Subject", message );

In my Outlook, the image is hidden and I have to click on Automatic download images.

I tried also to write image source as base64 code

string message = "<p><img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAR8AAAA8CA...' />";
SendEmail( "[email protected]", "[email protected]", "Subject", message );

but it doesn't work.

Upvotes: 1

Views: 2586

Answers (2)

onon15
onon15

Reputation: 3630

If the image is simple (i.e. not many colors, simple geometry) you can convert it into an HTML table, and then embed it in an HTML e-mail. You can use this open source tool to do the conversion.

Upvotes: 0

Ondrej Svejdar
Ondrej Svejdar

Reputation: 22094

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.

public void Email(string htmlBody, string emailSubject) {
  var mailMessage = new MailMessage("[email protected]", "[email protected]");
  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" }
  };
}

Upvotes: 1

Related Questions