使用vb.net嵌入未在电子邮件中显示的图像

时间:2011-02-10 15:36:46

标签: asp.net vb.net image system.net.mail

我正在尝试在电子邮件正文中显示嵌入图像。发送,但没有图像。

以下是代码:

Dim mail As New MailMessage()

mail.[To].Add("siu07aj@reading.ac.uk")

mail.From = New MailAddress("atiqisthebest@hotmail.com")

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)

在电子邮件正文中,只显示以下内容:

欢迎使用CodeDigest.Com !!

知道如何才能显示CIMG1443.JPG吗?

由于

1 个答案:

答案 0 :(得分:0)

您可以尝试使用以下方法将图像转换为base64字符串来内联图像:

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

然后使用类似的内容将图像添加到HTML中(其中 yourImage 是Image-class的一个实例):

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

通过这种方式,您可以将图像添加为资源。这在几个地方对我有用,尽管我必须承认我没有在hmlt电子邮件上试过它。

的Sascha