C#: Sends Emails Based on a Word Template with the .net Mail Library

Hello,

I will explain in this blog post how to send email with the .net mail library in C#, based on a Word document template and using inline image.

Actually what I’m doing:

I’m taking a Word document, this document is text formatted with color or whatever. In this document there are special encodings such as: “@@header@@”. Every encodings belong to one specific image.

I can then convert the Word document to Html and push the image with the inline specifications. One thing really important, image must have directly the correct size, otherwise the full image size will be taken.

To convert a Word document I’m using the OpenXML C# library from Microsoft (https://msdn.microsoft.com/en-us/library/office/bb448854.aspx ) and then I’m using the OpenXMLPowerTool library coming from Eric White (https://github.com/OfficeDev/Open-Xml-PowerTools  )

You can of course find those libraries directly from nugget.

The code below explain you how to convert Word to HTML and save it as HTML file:

byte[] byteArray = System.IO.File.ReadAllBytes("MYWORDPATH.docx");
using(MemoryStream memoryStream = new MemoryStream()) {
 memoryStream.Write(byteArray, 0, byteArray.Length);
 using(WordprocessingDocument doc = WordprocessingDocument.Open(memoryStream, true)) {
     HtmlConverterSettings settings = new HtmlConverterSettings()      {
          PageTitle = "My Page Title"
          //used for tag <title> of html page
      };
 XElement html = HtmlConverter.ConvertToHtml(doc, settings);

 System.IO.File.WriteAllText("Test.html", html.ToStringNewLineOnAttributes());
 }
}

The code below explain you how to add an inline image in a MailMessage C# object (called below mail) :

 // generate the contentID string
 string contentIDHeader = Guid.NewGuid() + "loicsterckx";
 // create the INLINE attachment
 string attachmentPathHeader = "MYHEADERIMAGE.png";
 System.Net.Mail.Attachment inlineHeader = new System.Net.Mail.Attachment(attachmentPathHeader);
 inlineHeader.ContentDisposition.Inline = true;
 inlineHeader.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
 inlineHeader.ContentId = contentIDHeader;
 inlineHeader.ContentType.MediaType = "image/png";
 inlineHeader.ContentType.Name = Path.GetFileName(attachmentPathHeader);
 mail.Attachments.Add(inlineHeader);

To reference your inline image in your Html body message:

I’m using here the cid in the src of the image the point to the image inlined.

bodyMessage = bodyMessage.Replace("@@header@@", "<img src=\"cid:" + contentIDHeader + "\"/>");

And now the full picture:

MailAddress to = new MailAddress("toAddress@friend.com");
MailAddress from = new MailAddress("fromAddress@friend.com");
MailMessage mail = new MailMessage(from, to);

mail.Subject = "My Mail Subject";

string bodyMessage;
byte[] byteArray = System.IO.File.ReadAllBytes("MYWORDPATH.docx");
using(MemoryStream memoryStream = new MemoryStream()) {
	memoryStream.Write(byteArray, 0, byteArray.Length);
	using(WordprocessingDocument doc = WordprocessingDocument.Open(memoryStream, true)) {
		HtmlConverterSettings settings = new HtmlConverterSettings() {
			PageTitle = "My Page Title"
			//used for tag <title> of html page

		};
		XElement html = HtmlConverter.ConvertToHtml(doc, settings);

		bodyMessage = html.ToStringNewLineOnAttributes();
	}
}

mail.IsBodyHtml = true;

// generate the contentID string using the datetime
string contentIDHeader = Guid.NewGuid() + "loicsterckx";
// create the INLINE attachment
string attachmentPathHeader = " MYHEADERIMAGE.png ";
System.Net.Mail.Attachment inlineHeader = new System.Net.Mail.Attachment(attachmentPathHeader);
inlineHeader.ContentDisposition.Inline = true;
inlineHeader.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inlineHeader.ContentId = contentIDHeader;
inlineHeader.ContentType.MediaType = "image/png";
inlineHeader.ContentType.Name = Path.GetFileName(attachmentPathHeader);
mail.Attachments.Add(inlineHeader);
bodyMessage = bodyMessage.Replace("@@header@@", "&lt;img src=\"cid:" + contentIDHeader + "\"/&gt;");

mail.Body = bodyMessage;

SmtpClient smtp = new SmtpClient();
smtp.Host = "MYSMTP";
smtp.Port = 25;

Console.WriteLine("Sending email...");
smtp.Send(mail);
Advertisements
This entry was posted in C# Solutions and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s