AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1411&pId=-1
Using LinkedResource Class for Sending HTML E-mail in .NET 2.0
page
by Soyuj Kumar Sahoo
Feedback
Average Rating: 
Views (Total / Last 10 Days): 62431/ 64

Introduction

This is the answer to one of the comments on my previous article by someone who was unable to use these codes to send images in Outlook and Hotmail. I guess the MIME source of that send mail is ok, but might be the problem in Mail clients for fetching information from the MIME source.

So I tried another approach for sending html mail with embedded image in .NET 2.0 applications.    

LinkedResource class

LinkedResource class is one of the important classes supported in System.Net.Mail for representing embedded external resource. These external resources are used in an email attachment or as an image in an HTML attachment. This is derived from the AttachmentBase class of System.Net.Mail namespace.

It is mainly used for creating embedded images in email. 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.

Supported Constructors

For initializing the new instance of LinkedResource, the .NET 2.0 Framework supports six overloaded constructors. These are used for setting different initial parameters with a common goal for getting the content of an embedded resource. These constructors are:

1.    LinkedResource (contentStream as System.IO.Stream): Initializes a new instance of LinkedResource using the supplied Stream.

2.    LinkedResource (fileName as String): Initializes a new instance of LinkedResource using the specified file name.

3.    LinkedResource (contentStream as System.IO.Stream, contentType as ContentType): Initializes a new instance of LinkedResource with the values supplied by Stream and ContentType.

4.    LinkedResource (contentStream as System.IO.Stream, mediaType as String): Initializes a new instance of LinkedResource with the specified Stream and MIME media type.

5.    LinkedResource (fileName as String, contentType as ContentType): Initializes a new instance of LinkedResource with the specified file name and content type.

6.    LinkedResource (fileName as String, mediaType as String): Initializes a new instance of LinkedResource with the specified file name and MIME media type.

Some useful properties of LinkedResource Class

The LinkedResource Class supports some public properties, which are useful in embedding attachment resource.

7.    ContentId: Gets or sets the MIME content ID for the attachment

8.    ContentLink: Gets or sets a URI that the resource must match

9.    ContentSteam: Gets the content stream of the attachment

10. ContentType: Gets the content type of the attachment

11. TransferEncoding: Gets or sets the encoding of the attachment

How to embed an image using LinkedResource class

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.

Listing 1 – Sample for HTML view

// to embed images, we need to use the prefix 'cid' in the img src value
string htmlBody = "<b>This is the embedded image file.</b><DIV> </DIV>";
htmlBody += "<img alt=\"\" hspace=0 src=\"cid:uniqueId\" align=baseline border=0 >";
htmlBody += "<DIV> </DIV><b>This is the end of Mail...</b>";
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, 
    null, "text/html");     

Then we need to create a LinkedResource object and add it to the AlternateView's LinkedResources Collection. Again, before adding this be sure to set the ContentId property of LinkedResource class as that unique value set in the HTML tag of AlternateView (i.e. cid). Here we need to set the TransferEncoding property of LinkedResource to Base64 which is the default for the image.

Listing 2 – Sample for Image resource

// create the image resource from image path using LinkedResource class..            
LinkedResource imageResource = new LinkedResource("c:\\attachment\\image1.jpg" , 
    "image/jpeg");
imageResource.ContentId = "uniqueId";
imageResource.TransferEncoding = TransferEncoding.Base64;

Here "uniqueId" is the common unique cid value. Let us add the above "imageResource" to "htmlView."

Listing 3 – Sample for adding Image in HTML part

// adding the imaged linked to htmlView...
htmlView.LinkedResources.Add(imageResource);

Then we have to add this htmlView (AlternateView object) to the MailMessage object.

Listing 4 – Setting the mail message

// add the view
mail.AlternateViews.Add(htmlView);
Sample codes

Listing 5 – C#

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
 
namespace Soyuj.HtmlMail
{
    class HtmlMail
    {
        private static string _mailServer = String.Empty;
 
        /// <summary>
        /// The starting function of console application.
        /// </summary>
        /// <param name="args">Parameters in CommandLine arguments</param>
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to Soyuj\'s Mail send application..");
            Console.WriteLine("Enter your Mail Server :: ");
            _mailServer = Console.ReadLine();
            EmbeddedImagesLinked();
            Console.WriteLine( "\r\n Completed...");
            Console.ReadLine();
 
        }
  
        /// <summary>
        /// Sends mail using SMTP client, it can use the IP of Server also
        /// </summary>
        /// <param name="mail">The SMTP server (MailServer) as String</param>
        private static void SendMail(System.Net.Mail.MailMessage mail)
        {
            // send the message using SMTP client
            SmtpClient smtp = new SmtpClient(_mailServer); 
            // _mailServer is the MailServer IP or Name
 
            // mail Server IP or NAME 
            smtp.Credentials = CredentialCache.DefaultNetworkCredentials;
            smtp.Send(mail);
 
        } //  End SendMail
                     
        /// <summary>
        /// Embeds image in an HTML body of MailMessage using LinkedResorce Class
        /// </summary>
        public static void EmbeddedImagesLinked()
        {
            // create the mail message
            MailMessage mail = new MailMessage();
 
            // set the addresses
            mail.From = new MailAddress("from@fromdomain.com"" Display Name");
            mail.To.Add("to@todomain.com");
            mail.To.Add("yourHotmailID@hotmail.com");
            mail.CC.Add("yourGmailID@gmail.com");
            mail.CC.Add("yourYahooID@yahoo.com");
 
         
            // set the content
            mail.Subject = "This is an embedded image mail";
            string palinBody = 
               "Plain text content, viewable by clients that don\'t support html";
            AlternateView plainView = AlternateView.CreateAlternateViewFromString(
                palinBody, null, "text/plain");
 
            // then we create the Html part to embed images,
            // we need to use the prefix 'cid' in the img src value
            string htmlBody = "<b>The embedded image file.</b><DIV> </DIV>";
            htmlBody += 
      "<img alt=\"\" hspace=0 src=\"cid:uniqueId\" align=baseline border=0 >";
            htmlBody += "<DIV> </DIV><b>This is the end of Mail...</b>";
            AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
                htmlBody, null, "text/html");
 
            // create image resource from image path using LinkedResource class..            
            LinkedResource imageResource = new LinkedResource(
                 "c:\\attachment\\image1.jpg""image/jpeg");
            imageResource.ContentId = "uniqueId";
            imageResource.TransferEncoding = TransferEncoding.Base64;
 
            // adding the imaged linked to htmlView...
            htmlView.LinkedResources.Add(imageResource);
 
            // add the views
            mail.AlternateViews.Add(plainView);
            mail.AlternateViews.Add(htmlView);
 
            // send mail
            SendMail(mail);
 
        } // End EmbeddedImagesLinked
 
    } // End Class// End Namespace

Listing 6 – VB

Imports System.Net
Imports System.Net.Mail
Imports System.Net.Mime
 
Module SampleModule
 
    Private _mailServer As String = String.Empty
 
    ''' <summary>
    ''' The starting function of console application.
    ''' </summary>
    ''' <remarks>Need to set the mail server details from console</remarks>
    Sub Main()
 
        Console.WriteLine("Welcome to Soyuj's Mail send application..")
        Console.WriteLine("Enter your Mail Server :: ")
        _mailServer = Console.ReadLine()
 
        EmbeddedImagesLinked()
 
        Console.WriteLine(ControlChars.CrLf & "Completed...")
        Console.ReadLine()
 
    End Sub
 
    ''' <summary>
    ''' Sends mail using SMTP client
    ''' </summary>
    ''' <param name="mail">The SMTP server (MailServer) as String</param>
    ''' <remarks>It can use the IP of Server also</remarks>
    Private Sub SendMail(ByVal mail As Mail.MailMessage)
 
        'send the message using SMTP client
        Dim smtp As New SmtpClient(_mailServer) 'mail Server IP or NAME 
        smtp.Credentials = CredentialCache.DefaultNetworkCredentials
        smtp.Send(Mail)
 
    End Sub ' End SendMail
    
    ''' <summary>
    ''' Embedes an image in a Html body of MailMessage using LinkedResorce Class
    ''' </summary>
    ''' <remarks>Image tag must be in html body with 'cid' as src value</remarks>
    Public Sub EmbeddedImagesLinked()
 
        'create the mail message
        Dim mail As New MailMessage()
 
        'set the addresses
        mail.From = New MailAddress("from@fromdomain.com"" Display Name")
        mail.To.Add("to@todomain.com")
       
        'set the content
        mail.Subject = "This is an embedded image mail"
 
        'first we create the Plain Text part
        Dim palinBody As String = 
"This is my plain text content, viewable by those clients that don't support html"
        Dim plainView As AlternateView = 
AlternateView.CreateAlternateViewFromString(palinBody, Nothing"text/plain")
 
        'then we create the Html part
        'to embed images, we need to use the prefix 'cid' in the img src value
        Dim htmlBody As String = 
"<b>This is the embedded image file.</b><DIV>&nbsp;</DIV>"
        htmlBody += 
"<img alt="""" hspace=0 src=""cid:uniqueId"" align=baseline border=0 >"
        htmlBody += "<DIV>&nbsp;</DIV><b>This is the end of Mail...</b>"
        Dim htmlView As AlternateView = 
AlternateView.CreateAlternateViewFromString(htmlBody, Nothing"text/html")
 
        'create the image resource from image path using LinkedResource class..
        Dim imageResource As New LinkedResource(
"c:\attachment\image1.jpg", "image/jpeg")
        imageResource.ContentId = "uniqueId"
        imageResource.TransferEncoding = TransferEncoding.Base64
 
        'adding the imaged linked to htmlView...
        htmlView.LinkedResources.Add(imageResource)
 
        'add the views
        mail.AlternateViews.Add(plainView)
        mail.AlternateViews.Add(htmlView)
        'mail.AlternateViews.Add(imageView)
 
        'send mail
        SendMail(mail)
 
    End Sub ' End EmbedImages
 
End Module ' End SampleModule

NOTE: Before using the above code, be sure to set your email addresses in the required place with Mail Server (SMTP).

Conclusion

I hope this article is helpful for sending embedded image mail in .NET 2.0. I guess this process is working fine with all the mail clients and all the Web mail sites like Hotmail, Gmail, Yahoo!, AOL, etc. Let me know if any further issues arise.

By Soyuj Kumar Sahoo

 


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-20 12:27:36 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search