Send mails in both HTML and Text Format using VB.NET / Automatically direct messages in HTML / Text format using .NET
Imports System.Net.Mail
Imports System.Net.Mime
Imports System.ComponentModel
Sub Create_HTML_Mail_With_Embedded_Images()
Dim oMailMsg As MailMessage
Dim oSMtPClient As SmtpClient
Dim sTEXTBody As String
Dim avTEXTBody As AlternateView
Dim sHTMLBody As String
Dim avHTMLBody As AlternateView
oMailMsg = New MailMessage
oMailMsg.From = New MailAddress("sample@dotnetdud.com", "Dot Net Dud Sample")
' If you do not use the constructor and add address using To.Add you can add more addresses
oMailMsg.To.Add(New MailAddress("subscriber@dotnetdud.com", "Feed Subscribers"))
oMailMsg.To.Add(New MailAddress("techwriters@dotnetdud.com", "Tech Writers"))
oMailMsg.Subject = "Welcome to Mailing List"
sHTMLBody = " <> <> <> Welcome to DotNetDud Mailing List < /H1 > <> You will get mails on .... < /P > <> < src=""> < /body > < /HTML > "
sTEXTBody = "Welcome to DotNetDud Mailing List < /H1 > <> You will get mails on .... (Some images are not rendered due to text formatting)"
'Error Name 'mediatypenames' is not declared will come if Imports System.Net.Mime is not present
avHTMLBody = AlternateView.CreateAlternateViewFromString(sHTMLBody, Nothing, MediaTypeNames.Text.Html)
avTEXTBody = AlternateView.CreateAlternateViewFromString(sTEXTBody, Nothing, MediaTypeNames.Text.Plain)
' Creating Linked Resources
Dim img1 As LinkedResource = New LinkedResource("c:\temp\Img1.jpg", MediaTypeNames.Image.Jpeg)
img1.ContentId = "Img1"
avHTMLBody.LinkedResources.Add(img1)
oMailMsg.AlternateViews.Add(avHTMLBody)
oMailMsg.AlternateViews.Add(avTEXTBody)
oSMtPClient = New SmtpClient("smtp.dotnetdud.com")
oSMtPClient.Send(oMailMsg)
End Sub
LinkedResource represents an embedded external resource in an email attachment, such as an image in an HTML attachment. We use it to create a new linked resource to the image and set the MIME content ID for this attachment as Img1. The same is represented in the HTML tag as CID ( < src=""> ). The image will be rendered in appropriate position in the email
Use the AlternateViews property to specify copies of an e-mail message in different formats. For example, if you send a message in HTML, you might also want to provide a plain text version in case some of the recipients use e-mail readers that cannot display HTML content.
To add an alternate view to a MailMessage object, create an Attachment for the view, and then add it to the collection returned by AlternateViews. Use the Body property to specify the text version and use the AlternateViews collection to specify views with other MIME types. Use the MediaTypeNames class members to specify the MIME type for the alternate view.
Linked Resources in VB.NET, Alternate Views in .Net, Embed images in eMail messages using .NET, Embed Pictures in mail using .NET, HTML with embedded messages using .NET