Embedded images in email not showing (.NET 3.5)

1.3k Views Asked by At

In .NET/C# 3.5 I build an email with embedded images, receives the email in smtp4dev (http://smtp4dev.codeplex.com/) but the images won't show. I use the HTML Agility Pack to parse a HTML document and do some cleaning (this part works fine).

//uninteresting code above

    var images = doc.DocumentNode.Descendants("img");

    List<MemoryStream> listOfStreams = new List<MemoryStream>();
    List<string> listOfCid = new List<string>();
    List<string> listOfReplacedSrcValues = new List<string>();

            foreach (var img in images)
            {
                var src = img.Attributes["src"];
                if (src != null && src.Value.StartsWith("http://"))
                {
                    listOfReplacedSrcValues.Add(src.Value);
                    //I build a string that looks like this inv_brandLogo_fr_gif
                    string cid = src.Value.Substring(src.Value.LastIndexOf('/'), src.Value.Length - src.Value.LastIndexOf('/')).Trim('/').Replace('.', '_');
                    string cidWithTimestamp = string.Format("cid:{0}_{1}", cid, DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fffffff")); //append a timestamp to ensure the cid is unique !
                    PageResult = PageResult.Replace(src.Value, cidWithTimestamp);
                    listOfCid.Add(cidWithTimestamp);

                    WebClient wc = new WebClient();
                    byte[] originalData = wc.DownloadData(src.Value);

                    MemoryStream ms = new MemoryStream(originalData);

                    listOfStreams.Add(ms);
                }
            }

            MailAlert.SendRecap(Context.User.Identity.Name, PageResult, listOfStreams, listOfCid);

//end of the 1st bit of code


public static void SendRecap(string connectedUser, string HTMLcontent, List<MemoryStream> listOfStreams, List<string> listOfCid)
        {
            try
            {
                SmtpClient sender = new SmtpClient();

                MailMessage message = new MailMessage();

                message.From = new MailAddress("[email protected]");
                message.To.Add(string.Format("{0}@vente-privee.com", connectedUser));
                message.Subject = "Test Recap";
                message.Body = HTMLcontent;
                message.IsBodyHtml = true;

                int i = 0;
                string plainBody = "Plain text content, viewable by clients that don\'t support html";
                AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainBody, null, "text/plain");
                AlternateView htmlView = AlternateView.CreateAlternateViewFromString(HTMLcontent, null, "text/html");

                //create the LinkedResource (embedded image)
                foreach (var ms in listOfStreams)
                {
                    ContentType ct = new ContentType();
                    if (listOfCid[i].Contains("gif"))
                    {
                        ct = new ContentType(MediaTypeNames.Image.Gif);
                    }
                    else if (listOfCid[i].Contains("jpg") || listOfCid[i].Contains("jpeg"))
                    {
                        ct = new ContentType(MediaTypeNames.Image.Jpeg);
                    }
                    else if (listOfCid[i].Contains("png"))
                    {
                        //contentType = "image/png";
                        ct = new ContentType(MediaTypeNames.Image.Jpeg);
                    }

                    LinkedResource imageResource = new LinkedResource(ms, ct);

                    imageResource.ContentId = listOfCid[i];
                    imageResource.TransferEncoding = TransferEncoding.Base64;

                    htmlView.LinkedResources.Add(imageResource);
                    i++;
                }

                message.AlternateViews.Add(plainView);
                message.AlternateViews.Add(htmlView);

                sender.Send(message);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

When I inspect the received email in smtp4dev, I can see all its parts on the left column "MIME Parts" :

  • Unnamed: multipart/alternative (158959 bytes)
    • Unnamed: text/plain (50642 bytes)
    • Unnamed: text/plain (65 bytes)
    • Unnamed: multipart/related (107752 bytes)
      • Unnamed: text/html (50642 bytes)
      • Unnamed: image/gif (4610 bytes)
      • Unnamed: image/jpeg (1908 bytes)
      • Unnamed: image/gif (540 bytes)
      • Unnamed: image/gif (544 bytes)
      • Unnamed: text/html (48466 bytes)

I can even select any of these images, click the Body tab, choose "Save as" and successfully open them in my favorite image viewer.

When I select the "Unnamed: text/html (50642 bytes)" line then Body tab, I can see the HTML source of the email and all the "cid:" (for instance : src="cid:inv_brandLogo_fr_gif_2013-01-04-18-50-34-4569409")

But if I click "Open" in smtp4dev, the email opens up in Internet Explorer without any image.

When IE opens, it shows a warning at the bottom : "Internet Explorer restricted this webpage from running scripts or ActiveX controls" and a button "Allow blocked content" which I click, to no avail...

I've read numerous sites/blogs but can't figure out why the embedded images won't show. What am I missing here ?

0

There are 0 best solutions below