Creating a HTML E-Mail with images from embedded resources

In my last post I described a way to create a PDF from HTML with images retrieved from embedded resources of a .NET library. Based on that I will show the necessary steps for using exactly the same images to create a HTML E-Mail. A common way I use in projects at Tekaris.

I use a similar XSLT to generate some HTML content:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                              xmlns:msxsl="urn:schemas-microsoft-com:xslt"
                              exclude-result-prefixes="msxsl">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
    <html>
      <head>
        <title>EmbeddedImage</title>
      </head>
      <body>
        <img src="cid:header_image" />
        <div>The image is stored as an embedded resource.</div>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

The src-attribute of the image tag contains a CID (MIME content ID) and references an inline attachment of the mail object with the name “header_image”. The following code shows how to add the image as inline content:

var att = new Attachment(ms, new ContentType("image/png"));
att.ContentDisposition.Inline = true;
att.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
att.ContentId = "header_image";
mailMessage.Attachments.Add(att);

Here is the complete code:

string html;

using (var xsltStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EmbeddedImage.Resources.Mail.xslt"))
{
	var reader = XmlReader.Create(xsltStream);
	var xslt = new XslCompiledTransform();
	xslt.Load(reader);

	using (var ms = new MemoryStream())
	{
		xslt.Transform(new XmlDocument(), new XsltArgumentList(), ms);
		ms.Position = 0;
		using (var r = new StreamReader(ms))
		{
			html = r.ReadToEnd();
		}
	}
}

var mailMessage = new MailMessage
{
	From = new MailAddress("sender@anydomain.com"),
	Subject = "Embedded image test",
	IsBodyHtml = true,
	Body = html
};

mailMessage.To.Add("recipient@anydomain.com");

using (var ms = Assembly.GetExecutingAssembly().GetManifestResourceStream("EmbeddedImage.Resources.image.jpg"))
{
	var att = new Attachment(ms, new ContentType("image/png"));
	att.ContentDisposition.Inline = true;
	att.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
	att.ContentId = "header_image";
	mailMessage.Attachments.Add(att);

	var smtp = new SmtpClient("my.mail.server");
	smtp.Send(mailMessage);
}

And the mail should look like this:

embedded_image_mail

Advertisements