Saturday, May 23, 2009

Send email with embedded Image

Recently one of my friend wanted to send email containing embedded image, similarly like we can do using Outlook. So I decided to create an example for him. To embed external resource in email we can use LinkedResource class provide in System.Net.Mail. In this article we will send email containing embedded image with smtp server as gmail.

Code:

Private Sub SendEmail()
Dim mail As New MailMessage("fromAddress@gmail.com", "toAddress@gmail.com")
mail.Subject = "This is an embedded image mail"
'create the image resource from image path using LinkedResource class..
Dim imageResource1 As New LinkedResource("C:\MyPhotos\Photo1.jpg", "image/jpeg")
imageResource1.ContentId = "uniqueId1"
imageResource1.TransferEncoding = TransferEncoding.Base64
Dim imageResource2 As New LinkedResource("C:\MyPhotos\Photo2.jpg", "image/jpeg")
imageResource2.ContentId = "uniqueId2"
imageResource2.TransferEncoding = TransferEncoding.Base64
Dim htmlBody As New StringBuilder
htmlBody.AppendLine("")
htmlBody.AppendLine("<b>LIST OF PHOTOS</b>")
htmlBody.AppendLine("</br></br>")
htmlBody.AppendLine("PHOTO 1")
htmlBody.AppendLine("<img alt="""" hspace=0 src=""cid:uniqueId1"" align=baseline border=0 >")
htmlBody.AppendLine("</br></br>")
htmlBody.AppendLine("PHOTO 2")
htmlBody.AppendLine("<img alt="""" hspace=0 src=""cid:uniqueId2"" align=baseline border=0 >")
htmlBody.AppendLine("</br></br>")
Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString(htmlBody.ToString, Nothing, "text/html")
'adding the imaged linked to htmlView...
htmlView.LinkedResources.Add(imageResource1)
htmlView.LinkedResources.Add(imageResource2)
mail.AlternateViews.Add(htmlView)
Dim smtp As New SmtpClient("smtp.gmail.com", 587)
'If smtp server requires SSL
smtp.EnableSsl = True
smtp.Credentials = New NetworkCredential("fromAddress@gmail.com", "SMTP Password")
smtp.Send(mail)
End Sub