Visual Basic 8 (2005)Windows Vista.NET 1.0Visual Studio .NET 2003Windows 2003WebForms.NET 1.1Visual Studio 2005Windows XP.NET 2.0HTML中级开发Visual StudioWindows.NETVisual BasicASP.NET
将普通电子邮件转换为嵌入式资源电子邮件






2.67/5 (2投票s)
本文档描述并提供了一个简短(未优化)的函数,可以将普通的 HTML 输入转换为带有嵌入资源的电子邮件。
引言
大家好,这是我的第一篇文章 ^^。我编写了这个小函数,它在工作中帮助了我,我想分享它。这个想法是将普通的 HTML 输入转换为一个函数,该函数将返回一个 AlternateView
对象,该对象可用于使用 VB/ASP.NET 邮件对象发送电子邮件。
嗯,这个函数**完全**没有经过优化,并且使用了一些正则表达式。顺便说一下,我对正则表达式也很陌生,因此,如果需要任何更改/优化,请告诉我。
Using the Code
这是一个简单的函数,它查找所有图像/CSS/JS(查找 URL、src 标签)资源并将它们链接到电子邮件。
这是代码
Public Function convertToEmbedResource(ByVal emailHtml$) As AlternateView
'This is the website where the resources are located
Dim webSiteUrl$ = "http://www.thewebsite.com/myresources/"
' The first regex finds all the url/src tags.
Dim matchesCol As MatchCollection = Regex.Matches(emailHtml, _
"url\(['|\""]+.*['|\""]\)|src=[""|'][^""']+[""|']")
Dim normalRes As Match
' I didnt knew how to declare a new LinkedResourceCol so i did this :
Dim resCol As AlternateView = _
AlternateView.CreateAlternateViewFromString("", _
Nothing, "text/html")
Dim resId% = 0
' Between the findings
For Each normalRes In matchesCol
Dim resPath$
' Replace it for the new content ID that will be embeded
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
' Clean the path
resPath = Regex.Replace(normalRes.Value, "url\(['|\""]", "")
resPath = Regex.Replace(resPath, "src=['|\""]", "")
resPath = Regex.Replace(resPath, "['|\""]\)", _
"").Replace(webSiteUrl, "").Replace("""", "")
' Map it on the server
resPath = Server.MapPath(resPath)
' Embed the resource
Dim theResource As LinkedResource = New LinkedResource(resPath)
theResource.ContentId = "EmbedRes_" & resId
resCol.LinkedResources.Add(theResource)
' Next resource ID
resId = resId + 1
Next
' Create our final object
Dim finalEmail As AlternateView = _
Net.Mail.AlternateView.CreateAlternateViewFromString(emailHtml, _
Nothing, "text/html")
Dim transferResource As LinkedResource
' And transfer all the added resources to the output object
For Each transferResource In resCol.LinkedResources
finalEmail.LinkedResources.Add(transferResource)
Next
return finalEmail
End Function
发送电子邮件
这是发送电子邮件的代码
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)