Search code examples
vb.netwebview2

Show images from HTMLBody of MailItem in WebView2


I have a form with a WebView2. I want to make it possible to drag and drop E-Mails from Outlook onto the form and show the HTMLBody in a WebView2. That works just fine with the following code:

 Dim outlookApp As New Application
 Await EMailView.EnsureCoreWebView2Async()

 For Each mailitem As MailItem In outlookApp.ActiveExplorer.Selection
     EMailView.NavigateToString(mailitem.HTMLBody)
     txt_Contact.Text = mailitem.SenderEmailAddress
 Next

The problem is images which are stored with content id's are not displayed in the WebView2. In the HTMLBody the source code for images looks like this: <img src="cid:hz_logo_2d6cf186-a43c-47f0-a185-5d763938f37c.png">

How can I make it possible to show the image anyway? I only get the broken image picture in the WebView, instead of the real image. Is there some way to implement the picture into the source code that is to be processed in the WebView?


Solution

  • I found a solution and will write this down here for people who might face the same problem.

    I look for the the string

    src="cid:
    

    and parse until the next "-sign (sotred in TempString). That way I get the filename of the e-mail-attachment. Then I download this attachment and build a base64-encoded string of the saved image file which replaces the above mentioned string:

    For Each att As Attachment In mailItem.Attachments
    If att.FileName = TempString Then
        att.SaveAsFile(System.Windows.Forms.Application.StartupPath & att.FileName)
        Dim base64String As String = Convert.ToBase64String(System.IO.File.ReadAllBytes(System.Windows.Forms.Application.StartupPath & att.FileName))
        NewHTMLBody = NewHTMLBody.Replace("cid:" & TempString, "data:image/png;base64," & base64String)
    End If
    Next