Welcome to fuzzydev Sign in | Join | Help
in Search

.Net

System.Net.Mail - How to add Alternate views and Embed Images

System.Net.Mail provides us with a very intuitive object model to construct and send an email message.

These days almost all the web and windows email clients gives us more control over the email content we wish to view (a.k.a HTML view, plain text view). This is to make us aware that the email content we are viewing may contain explicit images or externally linked images. Now imagine the recipient have disabled HTML content in his/her settings then the email content will be displayed as is(with HTML tags).

We definitely don't want garbled text to be viewed by the recipient, now here is where the Alternate view comes to our rescue. As the name suggests it allows us to add alternate content that can be viewed by the receipient in case HTML content is disabled in his/her settings.

Similarly many web/windows email clients disable external images in the mail message to avoid linking of external images we can use the LinkedResource to embed images in our email message.

Although the core topic is about adding alternate views and embedding resources(images, etc) to an email, I will also touch upon configuration settings in web.config and Network Credentials.

MailMessage:

The MailMessage class plays a key role by wrapping all the email details like

  • From address
  • To address (collection)
  • CC address (collection)
  • BCC address (collection)
  • Email Subject
  • Email Body
  • Priority
  • Delivery notification options
  • Alternate views (Plain text, HTML)
  • Linked Resources (images, etc)

Below given is a typical code used to send an email, the code is pretty straight forward apart from the AlternateViews, LinkedResources and some SMTPClient config section.

//========================================================  
MailMessage objMailMessage = new MailMessage();

//File Attachment
if (fileUploadEmailAttachment.HasFile)
{
objMailMessage.Attachments.Add(
new Attachment(
fileUploadEmailAttachment.FileContent,
fileUploadEmailAttachment.FileName));

}

//From
objMailMessage.From = new MailAddress(txtEmailFrom.Text,
txtDisplayName.Text);

//To
objMailMessage.To.Add(new MailAddress(txtEmailTo.Text));

//CC
if (txtEmailCC.Text.Length > 0)
{
objMailMessage.CC.Add(new MailAddress(txtEmailCC.Text));
}

//BCC
if (txtEmailBCC.Text.Length > 0)
{
objMailMessage.Bcc.Add(new MailAddress(txtEmailBCC.Text));
}

//Subject
objMailMessage.Subject = txtSubject.Text;

//Plain Text Alternative Email Content
AlternateView objPlainAltView = AlternateView.CreateAlternateViewFromString(
txtAlternateView.Text);
objMailMessage.AlternateViews.Add(objPlainAltView);

//HTML Alternative Email Content
LinkedResource objLinkedRes = new LinkedResource(
Server.MapPath(".")
+ "\\fuzzydev-logo.jpg", "image/jpeg");
objLinkedRes.ContentId = "fuzzydev-logo";

AlternateView objHTLMAltView = AlternateView.CreateAlternateViewFromString(
txtHTMLBody.Text,
new System.Net.Mime.ContentType("text/html"));

objHTLMAltView.LinkedResources.Add(objLinkedRes);
objMailMessage.AlternateViews.Add(objHTLMAltView);

//High Priority
objMailMessage.Priority = MailPriority.High;

//Notify On Sucessfull Delivery
objMailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
SmtpClient objSMTPClient = new SmtpClient(txtHostName.Text);
objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.Network;

if(chkBoxEnableSSL.Checked)
objSMTPClient.EnableSsl = true;

//Credentials (username, password)
string sUserName = txtEmailFrom.Text.Split('@')[0];
objSMTPClient.Credentials = new System.Net.NetworkCredential(
sUserName, txtEmailFromPassword.Text);

//Send Email
objSMTPClient.Send(objMailMessage);

//========================================================

Now let me concentrate on the Alternateview, adding an alternate view is very easy, just create an object of the AlternateView class using the static method of the AlternateView class called CreateAlternateViewFromString passing the email text and the MIME type.

For example if we want to create a plain text view then we will do something like this

AlternateView objPlainAltView = AlternateView .CreateAlternateViewFromString(
txtAlternateView.Text);
objMailMessage.AlternateViews.Add(objPlainAltView);

Now if we need HTML view then

AlternateView objHTLMAltView = AlternateView.CreateAlternateViewFromString(
txtHTMLBody.Text,
new System.Net.Mime.ContentType("text/html"));
objMailMessage.AlternateViews.Add(objHTLMAltView);

That looks pretty simple, now the good news is the recipient will view the email message based on the email clients settings. So if HTML content is disabled then plain text message is displayed otherwise the HTML content is displayed.

Let us move forward and get our hands dirty by embedding an image in an HTML content message. In order to embed an image in our email we can use LinkedResource class, we can add this object to the LinkedResource collection of the AlternateView object.

LinkedResource objLinkedRes = new LinkedResource(
Server.MapPath(".")
+ "\\fuzzydev-logo.jpg",
"image/jpeg");
objLinkedRes.ContentId = "fuzzydev-logo";

AlternateView objHTLMAltView = AlternateView.CreateAlternateViewFromString(
"",
new System.Net.Mime.ContentType("text/html"));
objHTLMAltView.LinkedResources.Add(objLinkedRes);
objMailMessage.AlternateViews.Add(objHTLMAltView);

In the above code we are passing an image file path and also specifying the content type as an jpeg image to the LinkedResource object. Next line of code is very interesting, we are assigning a unique ContentId which will be used to set the src of our HTML image tag. In our case the content id is fuzzydev-logo and if you look at the HTML alternate view object in the constructor section we are having an image tag which refers to the same content id.

Now it's the email clients responsibility to understand the embedded resource and the reference in the image tag and display the image.

SMTPClient:

Now coming to the SMTP client configuration, let's just look in to what is the minimum configuration settings that SMTP client object expects from us.

  • Host name or IP address
  • Delivery Method (Network, Pick up directory from IIS, custom pickup directory)
  • EnableSsl (whether Secured Socket Layer is required)
  • Credentials (user name, password)

SMTPClient configuration in web.config:

	




userName="email user name"
password="email passowrd"
/>










The above configuration helps us in quickly changing the delivery method, from mail address, host name (or IP address) , user name and password. Although the configuration is not mandatory it is the recommended way of implementing the email functionality.

Below given code doesn't depend on the web.config for it's configuration needs

	SmtpClient objSMTPClient = new SmtpClient(txtHostName.Text);
objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.Network;
if(chkBoxEnableSSL.Checked)
objSMTPClient.EnableSsl = true;

//Credentials (username, password)
string sUserName = txtEmailFrom.Text.Split('@')[0];
objSMTPClient.Credentials = new System.Net.NetworkCredential(
sUserName, txtEmailFromPassword.Text);

//Send Email
objSMTPClient.Send(objMailMessage);

We don't need to specify the host name, etc if it's available in the web.config, this is usefull as in different part's of our application we can just use the specified configuration and if required then specify manually.

Now that deserves a round applause for those involved in the development of System.Net.Mail classes.

Published 23 July 2006 by sachinjoshi
Filed Under: ,
Anonymous comments are disabled

This Blog

Post Calendar

<July 2006>
SuMoTuWeThFrSa
2526272829301
2345678
9101112131415
16171819202122
23242526272829
303112345

Sponsored Links

Syndication

Copyright 2010, Sachin Joshi. All rights reserved.
The content on this site represents my own personal opinions and thoughts at the time of posting, and does not reflect those of my employer's in any way.
Powered by Community Server, by Telligent Systems