Solved

Embed Image ASP.Net Mail C#

Posted on 2008-10-20
28
1,515 Views
Last Modified: 2013-12-17
Hi,

I have looked on the net, and have gone through alot of examples but I still do not understand how this works and how I can refer to an existing html code.

I found this the following code online that may look useful to you but not me. In my code i have this:

        sb.Append("<body>");
        sb.Append("I put any HTML code here and images etc. I would like to place the image here);

that is where I would like to insert the image.

Regards,

introlux
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);

            

        }

Open in new window

0
Comment
Question by:introlux
  • 11
  • 11
  • 3
  • +2
28 Comments
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 22759351
see "Embedding an image into a HTML body" from http://www.emoreau.com/Entries/Articles/2007/09/Using-SystemNetMail.aspx
0
 
LVL 2

Expert Comment

by:tree33
ID: 22759434
Does that work for you?
        //Create the Mail object

        MailMessage mail = new MailMessage();

        mail.From = new MailAddress("me@domain.com");

        mail.To.Add("someone@domain.com");

        mail.Subject = "Mail with embedded image";

        mail.IsBodyHtml = true; 
 

        //Attach embedded images

        Attachment img1 = new Attachment( Server.MapPath(@"/Images/img1.gif"));

        img1.ContentId = "myPicture1";

        Attachment img2 = new Attachment( Server.MapPath(@"/Images/img2.gif"));

        img2.ContentId = "myPicture2";

        mail.Attachments.Add(img1);

        mail.Attachments.Add(img2);
 

        //Create the HTML body

        StringBuilder sb = new StringBuilder();
 

        sb.Append("<body>");

        sb.Append(@"<img src=""cid:myPicture1""/>");

        sb.Append(@"<img src=""cid:myPicture2""/>");

        sb.Append("</body>");
 

        mail.Body = sb.ToString();
 

        SmtpClient smtp = new SmtpClient("localhost");

        smtp.Send(mail);

Open in new window

0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22759488
What is your problme exactly? Understanding the code or running the code?
0
 

Author Comment

by:introlux
ID: 22765476
Hi tree33,

That code seems to work, but it adds the images as attachments which I would not want. I would prefer it to ONLY render it on the email body not show the user as an attachment.

Regards,

introlux
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22767358
Hi introlux,
Your own code seems fine to me. Have you tried it?
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22767374
Sorry, exception this line:
AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><img src=cid:companylogo/><br></body></html>" + strMailContent, null, MediaTypeNames.Text.Html);

Should be:
AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><img src=cid:companylogo><br>" + strMailContent + "</body></html>", null, MediaTypeNames.Text.Html);
 
0
 
LVL 2

Expert Comment

by:tree33
ID: 22768699
Did you try the code?
I'm using this, and the images are not visible as attachement, these are only embedded when setting the ContentId.
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22769035
>>>Did you try the code?
Yes, I did try your original code, not the expert's code (with the change I suggested in my last post) and it worked fine with me. I got an email with an image embeded in the email. (Isn't it what you want?) See the attached code snippet I used and also the screen shot of the email. (I commented "BCC" part, because some spam filter will catch emails with BCC)


string strMailContent = "Welcome new user";

string fromAddress = "yourname@yoursite.com";

string toAddress = "newuser@hisdomain.com";

string contentId = "image1";

string path = Server.MapPath(@"Images/FF3.jpg"); // I changed the logo image

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>" + strMailContent + "</body></html>", 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);

Open in new window

2008-10-21-114243.jpg
0
 

Author Comment

by:introlux
ID: 22774306
This looks like its working, but I am using stringbuilder method to do this.

StringBuilder sb = new StringBuilder();

        sb.Append("<html><head>");
        sb.Append(Environment.NewLine);
        sb.Append("<style>");
        sb.Append(Environment.NewLine);

etc............

How will I embed this with your code??
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22776797
First of all, not my code, it was your code I used. That is why I asked in my first post if you need help understand the code or execute the code.
Secondly, it does not matter at all how you construct your email body as long as it contains <img src=cid:companylogo> in the body. The following lines of code really do the magic to embed the image in the email body.
LinkedResource logo = new LinkedResource(path);
logo.ContentId = "companylogo";
// done HTML formatting in the next line to display my logo
AlternateView av1 = AlternateView.CreateAlternateViewFromString(strMailContent , null, MediaTypeNames.Text.Html);
av1.LinkedResources.Add(logo);
mailMessage.AlternateViews.Add(av1);

Of course, StringBuilder is the best choice for building the email body, you just need to append "<img src=cid:companylogo"> to the StringBuilder at the place where you want the image to be. then set strMailContent = sb.ToString(), and you can use your code to send emails.
 
0
 

Author Comment

by:introlux
ID: 22782137
So how will I use two images aswell, as this is the part im not clear about which is the

AlternateView av1 = AlternateView.CreateAlternateViewFromString(strMailContent

Also how many times will I need to use: strMailContent = sb.ToString()

Will this normally be placed at the end.

Regards,

introlux
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22782832
The StringBuilder sb is used to build your HTML formatted email body because it is very efficient and memory friendly, comparing to the string concatenation such as someString + someOtherStirng + someMoreString. So you only need do once: strMailContent = sb.ToString()

Please read this article for more information about StringBuilder and you will understand why it is preferable:

http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx

If you need two or more images, then you will need two or more "<img cid=image2>" "<img cid=image3>" when you build your email body. Each "cid" needs to be different for different image, then you will repeat those "magic" lines (see my post 22776797) for each image.

Am I confusing you more?
0
 

Author Comment

by:introlux
ID: 22812999
I am trying to embed what you have done with my code. I get the folloiwng error:

Compiler Error Message: CS1502: The best overloaded method match for 'System.Net.Mail.AlternateView.CreateAlternateViewFromString(string, System.Text.Encoding, string)' has some invalid arguments

Source Error:

 

Line 113:        logo.ContentId = "companylogo";
Line 114:        // done HTML formatting in the next line to display my logo
Line 115:        AlternateView av1 = AlternateView.CreateAlternateViewFromString(sb, null, MediaTypeNames.Text.Html);
Line 116:        av1.LinkedResources.Add(logo);
Line 117:        mm.AlternateViews.Add(av1);
 
Any idea what this means??
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22823327
It should be "sb.ToString()", not sb. The argument is String type, not StringBuilder type.
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Author Comment

by:introlux
ID: 22830001
It is now compiling - I am now recieving the following files: ATT136525.htm ATT136526.dat

Any idea why and what these files are for??
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22830045
Could you post your code?
0
 

Author Comment

by:introlux
ID: 22830097
Here you go!
    private void test()

    {

        MailMessage mm = new MailMessage();

        StringBuilder sb = new StringBuilder();

        sb.Append("<html><head>");

        sb.Append(Environment.NewLine);

        sb.Append("<style>");

        sb.Append(Environment.NewLine);

        sb.Append("a");

        sb.Append(Environment.NewLine);

        sb.Append("{");

        sb.Append(Environment.NewLine);

        sb.Append("text-decoration:none;");

        sb.Append("}");

        sb.Append(Environment.NewLine);

        sb.Append("</style>");

        sb.Append("</head>");
 

        //Attach embedded images

        string path = Server.MapPath("Images/logo.jpg");

        string path2 = Server.MapPath("Images/hr.gif");
 

        sb.Append("<body>");

        sb.Append(

            //Heading

            "<table width=100% border=0 cellspacing=0 cellpadding=0><tr><td align=center>" +

            "<table width=600 border=0 cellspacing=0 cellpadding=0><tr><td align=center> " +
 

            "<img src=cid:logo1 width=226 height=116 /></td></tr><tr><td valign=top>" +

            "<table width=100% border=0 cellspacing=0 cellpadding=0><tr><td valign=top align=left><h2 align=center>Test Email</a></h2> " +

            //Info

            "<img src=break1 width=560 height=3 /><p>Email has been created by Test </p>" +

            "<p>Download Test</p>" +

            //Download File

            "<p>Download</p>" +

            "<img src=break1 width=560 height=3 />" +

            "</td></tr></table></td></tr><tr><td valign=middle align=left =footer height=61>" +

            //Footer

            "</td></tr></table></td></tr></table>");
 

        sb.Append("<br><br>");

        sb.Append("</body>");

        sb.Append("</html>");
 

        LinkedResource logo = new LinkedResource(path);

        logo.ContentId = "logo1";

        AlternateView av1 = AlternateView.CreateAlternateViewFromString(sb.ToString(), null, MediaTypeNames.Text.Html);

        av1.LinkedResources.Add(logo);

        mm.AlternateViews.Add(av1);
 

        LinkedResource break1 = new LinkedResource(path2);

        break1.ContentId = "break";

        AlternateView av2 = AlternateView.CreateAlternateViewFromString(sb.ToString(), null, MediaTypeNames.Text.Html);

        av2.LinkedResources.Add(break1);

        mm.AlternateViews.Add(av2);
 

        mm.Body = sb.ToString();

        mm.Subject = "Test";

        mm.To.Add("test@test.com");

        mm.From = new MailAddress("test@test.com");

        mm.IsBodyHtml = true;
 

        SmtpClient sc = new SmtpClient("localhost", 25);

        sc.Send(mm);

    }

Open in new window

0
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 22830143
when you use AlternateView, you don't have to set the Body.

see http://www.emoreau.com/Entries/Articles/2007/09/Using-SystemNetMail.aspx
0
 

Author Comment

by:introlux
ID: 22830196
Even when taking out the <Body> tags it still does the same thing.
0
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 22830220
by Body, I meant the property of the MailMessage object:
mm.Body = sb.ToString();
0
 

Author Comment

by:introlux
ID: 22830256
even when taking this out, still same issue
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22830932
You need "cid" for each image:
Line 32: "<img src=cid:break1 width=560 height=3 /><p>Email has been created by Test </p>"
Do the same thing on Line 36.
Line 52: break1.ContentId = "break1";   / /it has to match the "cid" in the <img> tag.
Remove Line 57.

0
 

Author Comment

by:introlux
ID: 22831161
This file is the only one that is attached now. The .dat file is now gone.

ATT138521.htm

How can you get rid of this file??
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22831219
What email client are you using to receive emails?
0
 

Author Comment

by:introlux
ID: 22831313
MS Outlook 2007
0
 
LVL 22

Accepted Solution

by:
prairiedog earned 500 total points
ID: 22831509
Your email body is poorly formatted HTML. There are several errors in the HTML file, you will need to fix those errors.
1. Line 30, at the very end, there is a "</a>" tag, but there is no <a> tag anywhere in your email body. Remove "</a>".
2. Line 37, "=footer" does not make any sense.
3. This one may be ok without it, but it is a best practice: always put single quotes or double quotes around the attributes of HTML tags, for example, <table border='100%'>, or <table border="100%">
0
 

Author Closing Comment

by:introlux
ID: 31507835
Thanks
0
 

Expert Comment

by:nick_humlesen
ID: 24409304
embed image in email C#
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now