Using LinkedResource Class for Sending HTML E-mail in .NET 2.0
page 6 of 7
by Soyuj Kumar Sahoo
Feedback
Average Rating: 
Views (Total / Last 10 Days): 62446/ 63

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).


View Entire Article

User Comments

Title: hi   
Name: jagadeesh
Date: 2012-09-26 3:56:19 AM
Comment:
cdfgd
Title: Nice Article   
Name: Sankara Narayanan
Date: 2011-01-03 7:01:55 AM
Comment:
Thank you very much, i tried its working fine. i have one doubt how can i set background image? i tried as you mention, but i cant. please help me.

Thanks & Regards
Sankara Naryananan
Title: Thank you from Mexico   
Name: Marcelino Ramirez Maldonado
Date: 2010-05-07 9:29:02 PM
Comment:
Thank you. Together with your another article and this one, they are the best mail sending articles i have seen in my life!!

¡Muchas gracias!
Title: hi   
Name: Sumit Kalra
Date: 2010-04-18 3:03:57 AM
Comment:
Though this code image not display at IE8
Title: can you provide an example embedding into word (not mail)   
Name: Chuck Farah
Date: 2009-01-06 3:24:11 PM
Comment:
I am trying to provide an embedd type of feature only in a word doc downloaded to their pc. i have tried this by using the src property for the image.

i use response.Write(strBody)
Title: Will not send AlternateView through server   
Name: Nick
Date: 2008-01-25 7:26:57 AM
Comment:
Hi,

This is a great article, very well explained. There's is a problem I have with the AlternateView though.

I have had the code working great locally with some nice results, however when I transfer the files onto a server the AlternativeView seems to stop the mail from sending. I have commented this out and a plain mail message sends fine on the server. So i know everything works except for when I try and use the AlternateView.


Have you ever come across this proble?

Cheers
Title: Great   
Name: Esteban
Date: 2007-11-08 3:37:53 PM
Comment:
Great article, very usefull how to add the image, thanx once again!!!
tete

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


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