Sending HTML Mail with Embedded Image in .NET
page 9 of 10
by Soyuj Kumar Sahoo
Feedback
Average Rating: 
Views (Total / Last 10 Days): 63185/ 928

Sample source code

Let us check the steps for creating a sample Mail Sending application in Visual Basic 2005. We have to follow the steps below.

·         Open Visual Studio 2005 and create a new console application project. Named it "MailSendingApp."

·         Copy and paste the following codes in that module and named it "SampleModule.vb."

Listing 10 – Sample source code of Mail sending application

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()
 
        EmbeddedImages()
 
        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>
    ''' Sets the content of MailMessage for default(plain text)
    ''' </summary>
    ''' <remarks>This is accessible by all Mail Clients</remarks>
    Public Sub SendPlainMail()
 
        'create the mail message
        Dim mail As New MailMessage("from@fromdomain.com""to@todomain.com")
 
        'set the message content
        mail.Subject = "This is a plain text mail"
        mail.Body = "This is a sample body... for default Mail Clients.."
 
        'send the mail using SMTP Client
        Dim smtp As New SmtpClient("My Mail Server") 'mail Server IP or NAME 
        smtp.Send(mail)
 
    End Sub ' End SendPlainMail
 
    ''' <summary>
    ''' Sets the content of MailMessage for a Html body only
    ''' </summary>
    ''' <remarks>The Html body is created using standard html tags..</remarks>
    Public Sub SendHtmlMail()
 
        'create the mail message
        Dim mail As New MailMessage("from@fromdomain.com""to@todomain.com")
 
        'set the message content
        mail.Subject = "This mail has Html Body.."
        mail.Body = "body with html<b>bold</b> <font color=#336699>blue</font>"
        mail.IsBodyHtml = True
 
        'send mail
        SendMail(mail)
 
    End Sub ' End SendHtmlMail
 
    ''' <summary>
    ''' Sets the MailMessage content with multiple body parts
    ''' (e.g a Html part and a PlainText part..)
    ''' </summary>
    ''' <remarks>Plain body is for Mail Clients, 
    ''' those don't support Html</remarks>
    Public Sub MultiPartMailBody()
 
        'create the mail message
        Dim mail As New MailMessage("from@fromdomain.com", "to@todomain.com")
 
        'set the message header
        mail.Subject = " This is a Multipart mail with hight Priority"
        mail.Priority = MailPriority.High
 
        'first we create the Plain Text part
        Dim plainView As AlternateView =
            AlternateView.CreateAlternateViewFromString(
            "Plain text content, viewable by clients that don't support html",
            Nothing"text/plain")
        mail.AlternateViews.Add(plainView)
 
        'then we create the Html part
        Dim htmlView As AlternateView = 
            AlternateView.CreateAlternateViewFromString(
            "<b>bold text, viewable by mail clients that support html</b>",
            Nothing"text/html")
        mail.AlternateViews.Add(htmlView)
 
        'send mail
        SendMail(mail)
 
    End Sub ' End MultiPartMailBody
 
    ''' <summary>
    ''' Set the MailMessage instance for multiple recipients with attachment
    ''' </summary>
    ''' <remarks>From address can be customized to show a Display Name</remarks>
    Public Sub MultipleRecipients()
 
        'create the mail message
        Dim mail As New MailMessage()
 
        'set the addresses
        '-----------------------------------
        'to specify a friendly 'from' name, we use a different display name
        mail.From = New MailAddress("from@fromdomain.com""Display Name")
 
        'since the To, Cc, and Bcc properties are collections, to add multiple
        'addreses, we simply call .Add(...) multple times
        mail.To.Add("to@todomain.com")
        mail.To.Add("to2@to2domain.com")
        mail.CC.Add("cc1@cc1domain.com")
        mail.CC.Add("cc2@cc2domain.com")
        mail.Bcc.Add("bcc1@bcc1domain.com")
        mail.Bcc.Add("bcc2@bcc2domain.com")
        '-----------------------------------
 
        'set the mail content
        mail.Subject = "This is an email with attachment"
        mail.Body = "This is the body content of the email."
 
        'set the attachment
        mail.Attachments.Clear()
        Dim attachment1 As New Attachment("c:\attachment\image1.jpg")
        mail.Attachments.Add(attachment1)
        mail.Attachments.Add(New Attachment("c:\attachment\text1.txt"))
 
        'send mail
        SendMail(mail)
 
    End Sub ' End MultipleRecipients
 
    ''' <summary>
    ''' Embeds an image in a Html body of MailMessage
    ''' </summary>
    ''' <remarks>The standard image tag must be there in html body with 'cid' 
    ''' in src value</remarks>
    Public Sub EmbeddedImages()
 
        '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 = 
          "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>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 AlternateView for embedded image
        Dim imageView As New AlternateView("c:\attachment\image1.jpg",
            MediaTypeNames.Image.Jpeg)
        imageView.ContentId = "uniqueId"
        imageView.TransferEncoding = TransferEncoding.Base64
 
 
        '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
 

·         Change the To, From, Cc, Bcc, etc. address to your type (but must be valid).

·          Press F5 to start debugging and follow the instructions from the console.

Figure 1- (sample console)

·         Enter your Mail Server address.

·         Check the output mail in your Mail Box. My sample output is:

Figure 2 - (Output sample mail)

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


View Entire Article

Article Feedback

Title:  
Name:  
Url: ( Optional )
Comment:  
Please add 6 and 5 and type the answer here:

User Comments

Title: OWA, Hotmail, Yahoo and Googlemail   
Name: Pieter
Date: 10/7/2009 4:57:21 PM
Comment:
\
Title: OWA   
Name: Pieter
Date: 10/7/2009 3:55:53 PM
Comment:
My last comment did not include this line which breaks it for Exchange Web Access:
data.Name = "image2.jpg";

Sorry...
Title: Hotmail   
Name: Pieter
Date: 10/7/2009 3:34:16 PM
Comment:
Hi
Thanks for the GREAT post. After fighting a bit with the image displaying in Hotmail, I came up with this code which seems to make it work:
Attachment data = new Attachment(imageView.ContentStream, MediaTypeNames.Image.Gif);
data.ContentDisposition.Inline = true;
data.ContentId = "uniqueId";
data.TransferEncoding = TransferEncoding.Base64;
message.Attachments.Add(data);

Just use that instead of the message.AlternateViews.Add(imageView);

Hopefully this will help someone.
Title: So cool, thanks.   
Name: Richard
Date: 7/2/2009 2:56:31 PM
Comment:
In stead of sending the embedded image email, How can we save it into the .eml template file?
Title: this is good   
Name: Harish kanzariya
Date: 7/2/2009 1:37:12 AM
Comment:
hi
Title: Error by using this codes   
Name: Nelson
Date: 5/28/2009 10:53:20 PM
Comment:
dear friends
this is very useful for me, when i put this codes to my code it was getting error like follows

Type 'MailMessage' is not defined
i think i have done some mistake, please help me to solve this problem

Thanks in ADvanced
Dim mail As New MailMessage
Title: embedded Email   
Name: Suresh
Date: 5/18/2009 7:03:04 AM
Comment:
Very Good Code. Thanks
Title: Works well, both google and yahoo   
Name: Sangam Uprety
Date: 3/27/2009 8:48:30 AM
Comment:
Hi Soyuj!
Thanks for the descriptive tutorial.
This has worked for me smart!
I could get the images embedded in my mail which displayed well in google mail (gmail) and yahoo mail. But I could not test it now with hotmail.

The only problem is that I cannot get it displayed in the mail readers that use plain view. The result is awsome- the image link is being displayed, with cid:uniqueid as src of the image. Looks ugly.

With best regards,
Sangam Uprety
http://dotnetspidor.blogspot.com
Title: This code is faulty   
Name: Vlax
Date: 11/29/2008 11:28:08 PM
Comment:
Look for another example in the net.
The attached image doesn't come right, you need to use "relatedfiles" or something like that instead of creating a additional AlternateView
Title: Need urgent help   
Name: Gandhi Basnet
Date: 11/22/2008 11:16:37 PM
Comment:
The code is working good now,
but the problem is when ever i am sending mail
the word "spam" is getting added to the subject
like if i send test it is like spam test in the subject line when i receive the mail

please help me out

thanks
Title: Works on Outlook Express but not for Outlook 2007   
Name: Gandhi Basnet
Date: 11/20/2008 3:58:33 AM
Comment:
The embedded image is displayed in Outlook Express but not in Outlook 2007.
Please help me out.
Title: Thanks and a great job   
Name: Chris
Date: 11/10/2008 2:30:00 PM
Comment:
I work in C#, and know little of VB.NET, but your code is just great and understandable still.

Congratulations!
Title: need help urgent   
Name: Geani
Date: 10/27/2008 10:18:25 AM
Comment:
I used same code. The only difference is the location of the image to be loaded. But, Image doesn't display properly.
It shows just an icon at the place of image. could u help me
Title: need help urgent   
Name: Rahul
Date: 10/9/2008 7:29:35 AM
Comment:
It was a nice article.
But Image doesn't display properly.
it shows just a icon at the place of image
could u help me

Thanks
Title: need help -urgent   
Name: sunil
Date: 8/20/2008 12:25:16 AM
Comment:
i tried ur code its working good
but the problem is when ever i am sending mail
the word "spam" is getting added to the subject
like if i send test it is like spam test in the subject line when i receive the mail

please help me out

thanks
Title: great job   
Name: bunny
Date: 8/18/2008 10:16:20 PM
Comment:
great work thanq very much for the post
i was working with web.mail some i got some issue with that
and ur code its really wow
thaks once again
Title: Gr8 buddy   
Name: Ankit Maini
Date: 6/27/2008 6:35:42 AM
Comment:
Thanx buddy nice article for me.
Title: asdasd   
Name: fasd
Date: 5/19/2008 9:20:06 PM
Comment:
asdf
Title: Mr   
Name: Baklouti
Date: 5/12/2008 10:44:50 AM
Comment:
Merci pour cet exposé bien fait; je l'ai testé et ça marche; j'ai remarqué sur mon test deux petits points :
1- le message sur yahoo était bien reçu image et texte, mais sur outlook express implémenté sur xp, l'image est bien arrivée et les caractères accentués sont mal interprétés
2- le message reçu sur outlook implémenté sur vista, est classé comme courrier indésirable et l'image n'est pas parvenu
auriez vous quelques idées pour corriger la situation
Merci
Title: For Local Host   
Name: Prince Mathew
Date: 2/19/2008 11:23:33 PM
Comment:
Thanks a lot... it saved much time...
Found some settings is needed to send thru localhost as server. Link provided will help

http://codebetter.com/blogs/peter.van.ooijen/archive/2006/04/05/Using-localhost-as-mailserver-_2800_5.7.1-Unable-to-relay-for-xxx_2900_.aspx
Title: View message before sending   
Name: Jerre
Date: 1/30/2008 9:23:19 AM
Comment:
I there a way to view the message in outlook 2003 first before sending it?
Title: Thank You Very Much...   
Name: Slawek
Date: 12/15/2007 7:05:52 PM
Comment:
Your article helped me very, very much and saved me much time. I think, you could add an examle how to authenticate on smtp server using login/password (single line at the end of this comment), and article will be truly complete
Slawek

smtp.Credentials = new System.Net.NetworkCredential(login,password)
Title: Imran   
Name: Imran Ali
Date: 11/6/2007 10:56:14 AM
Comment:
Hello ... Thank you ,,, It is very helpful
Title: ThankxxX   
Name: Mohammed. Akhtar
Date: 8/29/2007 6:18:45 AM
Comment:
It was very useful.
Title: Thanx To You   
Name: Sai
Date: 8/10/2007 1:28:03 AM
Comment:
Hello Sir,

I got good idea from this article but i expecting to know how can i read mails came to me in my gmail account in my asp.net application using POP3 Access.
Title: Pankaj   
Name: Pankaj Baviskar
Date: 8/7/2007 9:18:21 AM
Comment:
\
\
Title: Very good work   
Name: Jose
Date: 8/7/2007 2:36:54 AM
Comment:
Thank you Soyuj for this very good work. Each step is very well explained. Good job!
Title: Thanks!   
Name: Oscar
Date: 8/6/2007 11:53:30 AM
Comment:
Thanks a lot Soyuj! i'll try it that way
Title: Hotmail issue..   
Name: Soyuj Kumar
Date: 8/6/2007 3:41:14 AM
Comment:
Hello Oscar,

I have already checked with LinkedResource class and it is working fine for Hotmail.... try this..

Thanks.

Soyuj
Title: I am trying   
Name: Soyuj Kumar
Date: 8/6/2007 3:20:24 AM
Comment:
Hi...

Thanks for this nice questions!!! I have tried with Yahoo, Gmail, Hotmail... but got failed in Hotmail to see the image.. Yahoo and Gmail supports...

Please check the message source in all the experimental cases.. hello Kevin check the Outlook's source if the image source is there then we need to do some R&D..

BTW, another possible way is to try this action using "LinkedResource" which will take the path of the image.. and then (AlternateView)htmlView.add(LinkedResource) ....

So, please try with this...

Thanks,
Soyuj
Title: Thank You!   
Name: amin behzadi
Date: 8/4/2007 3:57:15 AM
Comment:
Excelent...! Very nice and clear to understandig.
thank you!
Title: Question   
Name: Oscar
Date: 8/3/2007 11:20:02 AM
Comment:
Excelent code Soyuj!! i have a question..the example works fine if i see the mail message in gmail(i see the text and the image), but in msnHotmail(i see the text and a gray box instead of the image) in mozilla i only see the image..
What could be the problem? is there any special setup that we need to see this mail correclty??
Thanks a lot!!!
Title: Thank, another question ask   
Name: Kevin
Date: 8/3/2007 2:43:25 AM
Comment:
your code got worked in outlook express, failed in outlook.

in outlook, i just saw a red cross instead of the pic. Do you know why or have you tested it like that?

any ideas please feel free to contact me via kevins@verdant.com.au. thanks again.

Cheers,
Kevin
Title: Thanks   
Name: Soyuj Kumar
Date: 8/2/2007 8:54:49 AM
Comment:
Thanks !!! for these nice comments...
Title: Enjoyed your article   
Name: Patricia
Date: 8/1/2007 10:33:58 PM
Comment:
Your writing style makes it so clear to understand. Thank you and looking forward to more of your articles.
Title: Nice work   
Name: John
Date: 7/27/2007 3:29:23 AM
Comment:
Nice work man.. Keep it up !!!

Product Spotlight
Product Spotlight 






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


©Copyright 1998-2009 ASPAlliance.com  |  Page Processed at 11/20/2009 10:17:34 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search