Private Function EmbedImages(ByRef messageBody As String) As System.Net.Mail.AlternateView
'Checks for the first image tag with priming read
Dim checkStart As Integer = messageBody.IndexOf("<img", 0)
Dim checkEnd As Integer = 0
Dim oldImageTag As String = Nothing
Dim newImageTag As String = Nothing
Dim field As String = Nothing
Dim alternateView As System.Net.Mail.AlternateView = Nothing
Dim linkedResourceArrayList As New ArrayList
Dim linkedResource As System.Net.Mail.LinkedResource = Nothing
Dim httpWebRequest As System.Net.HttpWebRequest = Nothing
Dim httpWebResponse As System.Net.HttpWebResponse = Nothing
'If an image tag was found, replaces it with the embedded image
Do While Not checkStart = -1
'Gets the whole image tag
checkEnd = messageBody.IndexOf(">", checkStart)
oldImageTag = messageBody.Substring(checkStart, (checkEnd - checkStart) + 1)
'Gets the image's src property
field = oldImageTag.Substring(oldImageTag.IndexOf("src") + 5)
field = field.Substring(0, field.IndexOf(""""))
'Links the image to embed
httpWebRequest = CType(System.Net.HttpWebRequest.Create(field), System.Net.HttpWebRequest)
httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials
httpWebResponse = CType(httpWebRequest.GetResponse(), System.Net.HttpWebResponse)
linkedResource = New System.Net.Mail.LinkedResource(httpWebResponse.GetResponseStream())
linkedResource.ContentId = "Image" & checkStart
'Set the image's new src property
newImageTag = oldImageTag.Replace(field, "cid:" & linkedResource.ContentId)
messageBody = messageBody.Remove(checkStart, (checkEnd - checkStart) + 1)
messageBody = messageBody.Insert(checkStart, newImageTag)
'Adds the resource to the alternate view
linkedResourceArrayList.Add(linkedResource)
'Checks for the next image tag
checkStart = messageBody.IndexOf("<img", checkStart + 4)
Loop
'Creates an alternate view with the embedded images
alternateView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(messageBody, Nothing, "text/html")
'Adds all the embedded images to the alternate view
For Each linkedResource In linkedResourceArrayList
alternateView.LinkedResources.Add(linkedResource)
Next
Return alternateView
End Function