Click here to Skip to main content
Click here to Skip to main content

Embed image in Email - ASP.NET , C#

By , 13 Dec 2007
 

Introduction

This is a simple article which tells you how you can embed images in emails. This can be very useful when you want to send emails from your website.A common scenario would be when a new user registers with your site and you want to send a welcome email with your site's logo on top.

I searched the net when I faced this issue. I am grateful to many authors from where I could make a  start. I have used their code while writing this. Due credit goes to them all. The intention is to make the code available for the others too.  To use this all you have to so is copy the code and paste it in any button click event.

This may only work with ASP.NET 2.0 & C#. I have tested it too. It will not run in ASP.NET 1.1.

 Namespaces Used

   using System.Net.Mail;
   using System.Net.Mime;

 

CODE

 // send mail to the new user who has registered.
   protected void yourButton_Click(object sender, EventArgs e)
    {
            
            string strMailContent = "Welcome new user";
            string fromAddress = "yourname@yoursite.com";
            string toAddress = "newuser@hisdomain.com";
            string contentId  = "image1";
            string path = Server.MapPath(@"images/Logo.jpg"); // my logo is placed in images folder
            MailMessage mailMessage = new MailMessage( fromAddress, toAddress );
            mailMessage.Bcc.Add("inkrajesh@hotmail.com"); // put your id here
            mailMessage.Subject = "Welcome new User";
          

            LinkedResource logo = new LinkedResource(path);
            logo.ContentId = "companylogo";
     // done HTML formatting in the next line to display my logo
            AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><img src=cid:companylogo/><br></body></html>" + strMailContent, null, MediaTypeNames.Text.Html);
            av1.LinkedResources.Add(logo);


            mailMessage.AlternateViews.Add(av1);
            mailMessage.IsBodyHtml = true;
            SmtpClient mailSender = new SmtpClient("localhost"); //use this if you are in the development server
                        mailSender.Send(mailMessage);
           
        }   

 Note:SmtpClient mailSender = new SmtpClient(ConfigurationManager.AppSettings["MyCustomId"]); // use this in the Production Server. I have specified my email server in the web.config file

Remarks

The image may not be displayed in Outlook Express. It worked well when the mail was viewed in Yahoo. If your site is not a trusted one there is a chance that the image may be blocked.  It did not work with Hotmail and Gmail.  

There are other ways to show images, but like many authors have pointed out they do not embed the image. They always refer to the parent site. The image won't be displayed when offline or when the location of the image has changed in the parent site

Do please send your comments . I would be happy to hear from you.

Thank you , Happy Coding !

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Rajesh C Medackel
Web Developer
India India
Member
A Mechanical Engineer, MBA working in Microsoft Technologies. Currently employed with a software major in Mumbai,India

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionI have been able to embed images in Gmailmemberelectriac3 Jan '13 - 9:33 
With the following:
  string str1 = textBox1.Text ; // Text before picture
                string str2 = textBox2.Text;  //Text after picture
                string htmltxt = "<html><body><h3>" + str1 + "<h3><img src=\"cid:image1 \"></body></html><h3>" + str2;  //Works!
                string fromAddress = textBox6.Text;
                string password = textBox7.Text;
                string photoPath = textBox4.Text;  // 230x347 will display there seems to be a size limitation in gmail
                MailMessage mailMessage = new MailMessage();
                mailMessage.From = new MailAddress(fromAddress);
                 for (int i = 0; i < listBox1.SelectedItems.Count; i++)
                {
                    mailMessage.To.Add(listBox1.SelectedItems[i].ToString());
                }
                mailMessage.Subject = textBox5.Text;
                LinkedResource photo = new LinkedResource(photoPath, MediaTypeNames.Image.Jpeg);
                photo.ContentId = "image1";
                AlternateView av1 = AlternateView.CreateAlternateViewFromString(htmltxt, null, MediaTypeNames.Text.Html);
                mailMessage.AlternateViews.Add(av1);
                av1.LinkedResources.Add(photo);
                mailMessage.IsBodyHtml = true;
                NetworkCredential credentials = new NetworkCredential(fromAddress, password);
                SmtpClient mailSender = new SmtpClient("smtp.gmail.com", 587);
                mailSender.Credentials = credentials;
                mailSender.Send(mailMessage);
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Success");
 

Questionhtml templates in asp.netgroupHari Chowdary8 May '12 - 21:38 
it's working good...
but i want to send html templates
QuestionPicture not adding to the body of the mailmemberHayden Pinto9 Mar '12 - 5:51 
Sub email_Monthly()
Dim myOutlook As Object
Dim myMailItem As Object
Dim emptyRow As Long
 
Set otlApp = CreateObject("Outlook.Application")
Set otlNewMail = otlApp.CreateItem(olMailItem)
 
Sheets(5).Activate
emptyRow = WorksheetFunction.CountA(Range("o:o"))
For i = 2 To emptyRow
 
j = Sheet5.Cells(i, 20)
t = Sheet5.Cells(i, 15)
f = Sheet5.Cells(i, 16)
n = Sheet5.Cells(i, 19)
 
With otlNewMail
.To = (j)
.Subject = ("Work Standards - " & f & " tasks need to be submitted")
.Importance = olImportanceHigh
.Body = ("Hi" & vbCrLf & n & "," & vbCrLf & vbCrLf & "The following " & f & " tasks need to be submitted by 12:00pm EST." & vbCrLf & vbCrLf & t & vbCrLf & vbCrLf & "Regards," & vbCrLf & I NEED TO ADD A PICTURE HERE )
' HOW DO I ADD A PICTURE - I DONT WANT TO USE HTML FORMAT
    On Error Resume Next
 
.Display
 
End With
   Next
Set otlNewMail = Nothing
Set otlApp = Nothing
Set otlAttach = Nothing
Set otlMess = Nothing
Set otlNSpace = Nothing
End Sub
Regards
Hayden,

GeneralMy vote of 2groupRajesh Duraisamy17 Aug '11 - 4:38 
its not working
GeneralChanges for it to work on Gmail and ThunderbirdmemberMember 786410722 Apr '11 - 1:32 
As Morcoveata wrote, removing the slash from the img tag at the end will make it work on MS Live email and I checked it also works on Gmail, but in Thunderbird it still doesn't work and the reason is the MIME type of the attached LinkedResource that is set to default generic
 
Content-Type: application/octet-stream
 
when the LinkedResource object is initialized with the default type.
 
To solve this and make it work also in Thuderbird, change the constructor to :

LinkedResource logo = new LinkedResource(path,"image/png");

 
(I was using a png so that is the type I worte, change it to your image type if it is another type, e.g., "image/jpeg")
 
Also,
You don't have to enter the whole HTML headers, so instead
 
<html><body><img src=cid:companylogo><br></body></html>
 
you can use just this
 

<img src=cid:companylogo>

GeneralMy vote of 1memberRam Shah22 Sep '10 - 23:50 
aishe hi
QuestionHow to display images in Windows Live Mail [modified]memberMorcoveata23 Aug '10 - 2:12 
Thanks, very useful article.
 
I made a very small change in the html markup and... ta-da... the image was displayed when I viewed the message in my Windows Live Mail client: <html><body><img src=cid:companylogo><br></body></html>.
The change is not closing the Image tag with "/>", but only with ">".
I didn't tested, but I suspect the same applies to Outlook and some other mail clients.

modified on Monday, August 23, 2010 8:21 AM

AnswerRe: How to display images in Windows Live MailmemberrurouniRonin3 May '11 - 9:12 
The better way would be to put a space between the src and close of the img tag so it would be like this:
<html><body><img src=cid:companylogo /><br></body></html>.
Generalthanks !memberaicha20089 Sep '09 - 0:56 
this help me , i use it ! thanks
Questionhow to send mail within intranet.membersudhir behera8 Sep '09 - 18:00 
i am final year student in computer science and engineering.i am doing my final year project in asp.net using c#.its a college automation system within intranet.in this project i want to implement mail server like gmail and also organisation chat service between student and faculty.please help me.i am running shortage of time.please send ur answer int his mail id:sudhirbehera09@gmail.com

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 14 Dec 2007
Article Copyright 2006 by Rajesh C Medackel
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid