Introduction
Hello all, this is my first article ^^. I did this little function that helped me out at the job, and I wanted to share it. The idea is to convert a normal HTML input to a function that will return an AlternateView
object that can be used to send an e-mail using the VB/ASP.NET mail objects.
Well, the function is not at all optmized, and uses a little of REGEX. And by the way, I am new to REGEX too, so, any changes/optimizations required, please let me know.
Using the Code
It's a simple function that finds all image/CSS/JS (finds URL, src tags) resources and link them to the e-mail.
Here is the code:
Public Function convertToEmbedResource(ByVal emailHtml$) As AlternateView
Dim webSiteUrl$ = "http://www.thewebsite.com/myresources/"
Dim matchesCol As MatchCollection = Regex.Matches(emailHtml, _
"url\(['|\""]+.*['|\""]\)|src=[""|'][^""']+[""|']")
Dim normalRes As Match
Dim resCol As AlternateView = _
AlternateView.CreateAlternateViewFromString("", _
Nothing, "text/html")
Dim resId% = 0
For Each normalRes In matchesCol
Dim resPath$
If Left(normalRes.Value, 3) = "url" Then
emailHtml = emailHtml.Replace(normalRes.Value, _
"url(cid:EmbedRes_" & resId & ")")
Else
emailHtml = emailHtml.Replace(normalRes.Value, _
"src=""cid:EmbedRes_" & resId & """")
End If
resPath = Regex.Replace(normalRes.Value, "url\(['|\""]", "")
resPath = Regex.Replace(resPath, "src=['|\""]", "")
resPath = Regex.Replace(resPath, "['|\""]\)", _
"").Replace(webSiteUrl, "").Replace("""", "")
resPath = Server.MapPath(resPath)
Dim theResource As LinkedResource = New LinkedResource(resPath)
theResource.ContentId = "EmbedRes_" & resId
resCol.LinkedResources.Add(theResource)
resId = resId + 1
Next
Dim finalEmail As AlternateView = _
Net.Mail.AlternateView.CreateAlternateViewFromString(emailHtml, _
Nothing, "text/html")
Dim transferResource As LinkedResource
For Each transferResource In resCol.LinkedResources
finalEmail.LinkedResources.Add(transferResource)
Next
return finalEmail
End Function
Sending the E-mail
Here is the code to send an email:
Dim mail As New MailMessage()
mail.From = New MailAddress("me@me.com")
mail.To.Add("me@me.com")
mail.Subject = " Embed Resources "
mail.AlternateViews.Add(convertToEmbedResource(" MY HTML EMAIL "))
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)