Question LinkedResource to embed image in Email(Images to be downloaded)?

BlackIce

Member
Joined
Jul 10, 2009
Messages
11
Location
Cape Town, South Africa
Programming Experience
1-3
Good Day

I am trying to embed images into an Email. The problem is the images
must be read from a website(eg example.co.za) and the function I've written to create the mail and send it out
is breaking. I get the mails into my pickup folder but I get an error msg saying sending the mail
failed and the images don't seem to have been embedded properly when I check the mails in my pickup. All the image paths are replaced
with cid:UniqueID but I still get asked to download my images by my mail client. I would appreciate any help with this matter.
The images cannot be acquired from a hard disk. All the examples regarding embedding on the internet give hard coded Drive paths
my function must loop through multiple URLs. I AM VERY LOST

My Code

VB.NET:
 Private Function SendEMail(ByVal fromemail As String, ByVal toemail As String, ByVal format As String, ByVal subject As String, ByVal message As String) As String
        Try
            Dim eResult As String
            Dim plainView As AlternateView
            Dim htmlView As AlternateView

            toemail = Replace(toemail, ";", ",")

            If Len(message) > 0 Then
                'create the mail message
                Using mail As New MailMessage
                    'set the addresses
                    mail.From = New MailAddress("listserve@dining-out.co.za")
                    mail.ReplyToList.Add(fromemail)
                    mail.To.Add(toemail)

                    'set the content
                    mail.Subject = subject

                    If LCase(format) <> "text" Then
                        Dim HTMLBody As String
                        Dim style As String = ""
                        Dim SSIndex As Integer
                        Dim SEIndex As Integer

                        'Split the message body and the CSS 
                        SSIndex = InStr(1, LCase(message), "<style")
                        SEIndex = InStr(1, LCase(message), "</style>")
                        If SSIndex > 0 And SEIndex > SSIndex Then
                            style = Mid(message, SSIndex, SEIndex - SSIndex + 8)
                            message = Mid(message, SEIndex + 8)
                        End If

                        'Build email
                        HTMLBody = "<!DOCTYPE HTML PUBLIC """"-//W3C//DTD HTML 4.0 Transitional//EN"""">" & vbCrLf & _
                        "<html>" & vbCrLf & _
                        "<head>" & vbCrLf & _
                        "<META http-equiv=Content-Type content=""""text/html; charset=us-ascii"""">" & vbCrLf & _
                        "<title>" & subject & "</title>" & vbCrLf & _
                        style & "</head>" & vbCrLf & _
                        "<body style=""color: navy;"">" & vbCrLf & _
                        message & "<br>" & vbCrLf & _
                       "</body>" & vbCrLf & _
                        "</html>" & vbCrLf

                        mail.IsBodyHtml = True
                        mail.BodyEncoding = System.Text.Encoding.ASCII
                        mail.Body = HTMLBody
                        'Embed, if any, images into the email
                        Dim reg As New Regex("src[^>]*[^/].(?:jpg|png|gif)(?:""|')")

                        'Dim messageOut As MailMessage = message
                        Dim msgString As String
                        msgString = mail.Body.ToString()

                        'This block will check if anything in the message body 
                        'is an image.
                        Dim match As Match
                        For Each match In reg.Matches(mail.Body)
                            Dim cid As String = Guid.NewGuid().ToString("N")
                            Dim srcStream As Stream

                            Dim src As String = match.Value
                            src = src.Replace("src=", "")
                            src = src.Replace("""", "")

                            'Check if image to be attached is on a website
                            If src.StartsWith("http://") Then
                                Dim request As Net.WebRequest = Net.HttpWebRequest.Create(src)
                                srcStream = request.GetResponse().GetResponseStream()

                            Else
                                srcStream = New MemoryStream(File.ReadAllBytes(src))
                            End If

                            htmlView = AlternateView.CreateAlternateViewFromString(msgString, Nothing, "text/html")
                            'Dim regexSearch As String = String.Format("{0}{1}", New String(Path.GetInvalidFileNameChars()), New String(Path.GetInvalidPathChars()))
                            'Dim r As New Regex(String.Format("[{0}]", Regex.Escape(regexSearch)))
                            'msgString = r.Replace(msgString, "")

                            'Dim imagelink As New LinkedResource(msgString, "image/jpeg")
                            Dim imagelink As New LinkedResource(srcStream)
                            imagelink.ContentId = "imageId"
                            imagelink.TransferEncoding = System.Net.Mime.TransferEncoding.Base64
                            htmlView.LinkedResources.Add(imagelink)
                            mail.AlternateViews.Add(htmlView)

                            'Add image to message body
                            'Dim newAttachment As New Attachment(srcStream, "image/" + Path.GetExtension(src).ToLower().Replace(".", ""))
                            'newAttachment.ContentId = cid
                            'messageOut.Attachments.Add(newAttachment)

                            mail.Body = mail.Body.Replace(src, "cid:" + cid)
                            srcStream.Dispose()
                        Next match

                        'Set up plain text and html mail formats
                        mail.Priority = MailPriority.High
                        plainView = AlternateView.CreateAlternateViewFromString(message, Nothing, "text/plain")
                        plainView.TransferEncoding = TransferEncoding.Base64
                        mail.AlternateViews.Add(plainView)
                    Else
                        mail.IsBodyHtml = False
                        mail.Body = message
                    End If
            'if we are using the IIS SMTP Service, we can write the message
            'directly to the PickupDirectory, and bypass the Network layer
            Dim smtp As New SmtpClient()
            smtp.PickupDirectoryLocation = "C:\inetpub\mailroot\Pickup"
            smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory
            'smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis
            smtp.Send(mail)
            eResult = "Successful"
            smtp = Nothing
            Return eResult
                End Using
            Else
                eResult = "Nothing to send"
                Return eResult
            End If
        Catch ex As Exception
            Return "Error"
        End Try
    End Function
 
You must keep all source streams alive until message is sent, these streams are read on demand when the message is transferring.
 
That could be because you are downloading from same server which could limit you to two simultaneous connections. In that case you would have to download the sources to files first, then use those files as attachments.
 
Back
Top