Linda
Linda

Reputation: 221

Create HTML img tag in ASP.NET code-behind using C#

I am trying to create an img tag in code-behind and send it in email (in the body of the email not as attachment).

body += "<p><img src='" + imageUrl.Remove(0,2) + "' alt='Product Image' width='250px' height='250px' runat='server' /></p>";

NB: I have declared body as string and I am adding other HTML controls to it (e.g p,h1,li etc).

The imageUrl variable returns "~/Images/bag/name_of_image.jpg" hence I am removing the first two characters which are ~/.

It seems like it is creating the image but its not displaying in the email body.

Upvotes: 0

Views: 8540

Answers (4)

Uğur Aldanmaz
Uğur Aldanmaz

Reputation: 1038

If you embed an image with its local path to an e-mail, this image cannot be accessible from remote receviers.

It is basic; user opens your e-mail using with any e-mail client program (outlook, thunderbird or webmail etc.), and e-mail client program searches this image using with its path. If path is a local, how can e-mail client program access this image?

You have to give a common accessible path that e-mail clients can access your image file and load then show it to user.

So upload your image to a server, then use the server address to specify image path.

An example:

string domainName = @"http://lindaLinda.com/images/";
string imageFileName = "myFirstEmailImg.jpg";
body += @"<p><img src='" + domainName + imageFileName +"' alt='Product Image' width='250px' height='250px' runat='server' /></p>";

It gives this output:

<p><img src='http://lindaLinda.com/images/myFirstEmailImg.jpg' alt='Product Image' width='250px' height='250px' runat='server' /></p>

Upvotes: 0

JJRS
JJRS

Reputation: 37

Please do it as below. just remove "~" from SRC.

 string mainUrl = "http://testURL.com/"; //its just example, you can put this in web config as well and than retrive it

 body += "<p><img src='" + mainUrl + imageUrl.Remove(0,1) + "' alt='Product Image' width='250px' height='250px' runat='server' /></p>";

Hope this will help you,

Thanks

Upvotes: 0

Ryan McDonough
Ryan McDonough

Reputation: 10012

You need include the absolute path to the image in the e-mail.

Images embedded in an email should be like:

<img src="http://www.example.com/image_link.jpg" alt="Some Image" />

You however in your email you would be embedding:

<img src="image_link.jpg" alt="Some Image" />

As the e-mail application the user has won't have a copy of image_link.jpg it can't show it.

So in your process you may need to upload the image to an externally accessible webserver (if being access outside your network) or at least an internally accessible web server.

Upvotes: 1

SpiderCode
SpiderCode

Reputation: 10122

I would suggest to use embedded image in your email body. Have a look at below URLs:

  1. http://www.emailarchitect.net/easendmail/kb/csharp.aspx?cat=8
  2. Send inline image in email

Upvotes: 0

Related Questions