Tuesday, December 14, 2010

Embed Image in email to avoid enabling downlod/display image in outlook, Gmail and other

There are scenarios when we need to send automated mail through our code with an image. Most of the time user has to click on the "display image" or "download image" to view the image in an email.

So, the better way to add the image into an email is to embed it in the email body. Beolw is the steps by which we can achieve this.

1. Following two namespace is to be used.
using System.Net.Mime;
using System.Net.Mail;


We will use "LinkedResource" class available in System.Net.Mail for representing embedded external resource.
To create the object of LinkedResource we need the content of the embedded resource as stream or need the path of that resource and then it is added to the HTML part of AlternateView's LinkedResources collection.

To create an embedded image we will need to first create an HTML view of the email using AlternateView class. Within that alternate view we need to create a tag that points to the ContentId (cid) of the LinkedResource of the image view as shown below:

//creating LinkedResource object with passing the path to the image to its constructor.
LinkedResource lrImage = new LinkedResource(Server.MapPath("images") + "\\" + "newsletter.gif");

//Set the content ID for the LinkedResouce object
        lrImage.ContentId = "newsletter";       

        string strmail = "";
        strmail = strmail + "";
        strmail = strmail + "";       
        strmail = strmail + "";
        strmail = strmail + "";
        strmail = strmail + "
";

 //add the image at the desired place using contentId(cid). BY default linkedResource ContentId is used    as cid:contentId. In our case the content id is "newsletter" so the image source would be the way as written below:
        strmail = strmail + "";
        strmail = strmail + "
";
        strmail = strmail + "";

// Now we need to create a Alternate view for the strmail.

 AlternateView av = AlternateView.CreateAlternateViewFromString(strmail, null, MediaTypeNames.Text.Html);
//now add the lrImage LinkedResource object to Alternate view
av.LinkedResources.Add(lrImage);

Now our "strMail" is ready to be send as email body.