Sending HTML emails with attachments in ASP.NET
Posted on 11 June 2009 by Jason Grimme
I’ve recently been working on a small project that deals with sending out emails to several different users on a Windows server.
.NET is pretty well documented and I did not have a very tough time writing a function that did what I needed. Not very difficult stuff, but hey, I needed content for my first blog post!
This function takes in a HTML message, text message, and a recipient address and sends out an email, as well as includes an attachment – one inline and one as a normal attachment. An inline attachment can be included in an HTML email (most usually an image).
You can include an inline attached image in your HTML by referencing it’s CID.
1 | <img src="cid:attached_image.gif" alt="" /> |
Here is my vb.net function, feel free to use:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | Function mailMessage(ByRef htmlMessageBody As String, ByRef textMessageBody As String, ByRef toAddress As String, ByVal attachedFilePath As String) As Boolean Dim objMail As New MailMessage objMail.From = New MailAddress("you@you.com") objMail.To.Add(toAddress) objMail.Subject = "Message Subject" objMail.Body = htmlMessageBody objMail.IsBodyHtml = True ' If we chose to attach a file, attach it If attachedFilePath.Length > 0 Then Dim attachedFile As Attachment = New Attachment(attachedFilePath) objMail.Attachments.Add(attachedFile) End If ' Create the text/plain version Dim txtView As AlternateView = AlternateView.CreateAlternateViewFromString(textMessageBody, Nothing, "text/plain") ' Attach text/plain version to the email objMail.AlternateViews.Add(txtView) ' Create inline image ' Image is in the directory this script is running from. you could have one uploaded. Dim Attch_CSLogo As LinkedResource Dim imgPath As String = Server.MapPath("inlineimage.gif") Attch_CSLogo = New LinkedResource(imgPath, "image/gif") Attch_CSLogo.ContentId = "YOURIMAGE_CID" ' Create the text/html version Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString(htmlMessageBody, Nothing, "text/html") ' Attach inline image htmlView.LinkedResources.Add(Attch_CSLogo) ' Attach text/html version to the email objMail.AlternateViews.Add(htmlView) 'Send our message Dim smtp As New SmtpClient("localhost") Try smtp.Send(objMail) Catch ex As Exception Return False Finally objMail.Dispose() smtp = Nothing End Try Return True End Function |
Tags | asp.net, attachment, inline attachment, send email, vb, vb.net
