1

I have an image stored in sql server. I want to retrieve the image and place it in a MailMessage object, not as an attachment file, but as part of the html body.

I found many samples using local image file, but I have not found any using an image from a database.

Anyone know how I can do this in vb.net?

Thank you in advance!

Javier

Eric LaForce
  • 2,125
  • 15
  • 24
jcamacho
  • 818
  • 2
  • 12
  • 25
  • 1
    See http://stackoverflow.com/questions/6261956/how-to-embed-an-image-stream-to-mailmessage. Though it doesn't pull the image from the database it does show you how to embed an image that does not come from a local filepath. You can combine this code with code to retrieve the image from the database into a memory stream – Eric LaForce Nov 09 '11 at 12:20

2 Answers2

0

You have to add the image from the database as a LinkedResource. When you retrieve the image as bytes from the database, you can add the LinkedResource using a stream; by creating a memorystream from the bytes.

Code in C#, but I think you should be able to convert this to VB.Net

var view = System.Net.Mail.AlternateView.CreateAlternateViewFromString(text, null, "text/html");
var resource = new System.Net.Mail.LinkedResource(new MemoryStream(bytes), mime);
resource.ContentId = image.Name;
view.LinkedResources.Add(resource);
_message.AlternateViews.Add(view);
Ruben
  • 6,367
  • 1
  • 24
  • 35
  • Do you know why in gmail account this images doesn't show?, in outlook, with an other internet mail account configured, the image is shown correctly?... I try to insert image as attachment, in this case, outlook show the image correctly too, but in gmail show as an attachment, doesn't show in html body ... – jcamacho Nov 09 '11 at 18:37
0

you have to include the image in the htmlbody with an imagetag: <img src="cid:myuniqueid" alt="img" />

By adding a LinkedResource you can include the image to the message. But you need to create a link between html body and the image. this is the "cid:myuniqueid" from the html body. The value of cid must be equal to the value of the ContentID Property of the LinkedResource Object.

Here is an example:

     '** Create MailMessage Object
     Dim message As New MailMessage()

     '** Create HTML view
     Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString(htmlbody, System.Text.Encoding.Default, MediaTypeNames.Text.Html)

     '** Create resource for the image
     Dim lr As New LinkedResource(objStream)

     '** Set the contentid for the image resource
     lr.ContentId = "myuniqueid"

     '** Link image resource and htmlview together
     htmlView.LinkedResources.Add(lr)

     '** Add view to MailMessage Object
     message.AlternateViews.Add(htmlView)
Nicholas
  • 754
  • 9
  • 28