embedding image not displaying in emaill using vb.net

1.3k Views Asked by At

I am trying to display an embed an image within the body of an email. The is sent, however without the image.

Below is the code:

Dim mail As New MailMessage()

mail.[To].Add("[email protected]")

mail.From = New MailAddress("[email protected]")

mail.Subject = "Test Email"


Dim Body As String = "<b>Welcome to codedigest.com!!</b><br><BR>Online resource for .net articles.<BR><img alt="""" hspace=0 src=""cid:imageId"" align=baseline border=0 >"

Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString(Body, Nothing, "text/html")

Dim imagelink As New LinkedResource(Server.MapPath(".") & "\uploads\CIMG1443.JPG", "image/jpg")

imagelink.ContentId = "imageId"

imagelink.TransferEncoding = System.Net.Mime.TransferEncoding.Base64

htmlView.LinkedResources.Add(imagelink)

mail.AlternateViews.Add(htmlView)

Dim smtp As New SmtpClient()

smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis
smtp.Host = ConfigurationManager.AppSettings("SMTP")
smtp.Port = 587
'smtp.EnableSsl = True

smtp.Credentials = New System.Net.NetworkCredential(ConfigurationManager.AppSettings("FROMEMAIL"), ConfigurationManager.AppSettings("FROMPWD"))

smtp.Send(mail)

In the body of the email only the following is display:

Welcome to CodeDigest.Com!!

Any idea how I can get the CIMG1443.JPG displaying?

Thanks

1

There are 1 best solutions below

0
On

you could try to inline the image, by converting it to a base64-string with the following method:

Public Function ImageToBase64(image As Image, format As System.Drawing.Imaging.ImageFormat) As String
    If image Is Nothing Then Return ""

    Using ms As New MemoryStream()
        ' Convert Image to byte[]
        image.Save(ms, format)
        Dim imageBytes As Byte() = ms.ToArray()

        ' Convert byte[] to Base64 String
        Dim base64String As String = Convert.ToBase64String(imageBytes)
        Return base64String
    End Using
End Function

Then you add the image to your HTML using something like this (where yourImage is an instance of the Image-class):

dim imageString = "<img src=""data:image/png;base64," + ImageToBase64(yourImage, ImageFormat.Png) + "="" />"

That way you would get around adding the image as resource. This worked for me in several places, even though I must admit that I haven't tryed it on hmlt emails.

Sascha