Sending mails using .NET 2.0

Sending mails using .NET 2.0 is extremely easy. Thought I’d give a quick example, this one with a file-attachement.

Imports

System.Net.Mail

Private Sub SendEmail(ByRef FileToSend As String)

‘Creating the SMTP-connection (this one stored in web.config)
Dim smtp As New SmtpClient(ConfigurationManager.AppSettings(“smtpHost”).ToString)

‘Creating the actual mail-object
Dim mail As New MailMessage

‘The attachment (reference to a file)
Dim att As New Attachment(FileToSend)

‘If errors should happen
Try

‘Send mail from this address
mail.From = New MailAddress(“sender@domain.tld”)

‘Send mail to this address
mail.To.Add(“mailto@domain.tld”)

‘Send BCC-copy to this address (use CC like this)
mail.Bcc.Add(“someone@someotherdomain.tld”)

‘Adding the subject (taken from a text-box)
mail.Subject = txtSubject.Text

‘Adding the body-text (taken from a text-box
mail.Body = txtContent.Text

‘Add the attachment
mail.Attachments.Add(att)

‘Send the e-mail using the SMTP-connection
smtp.Send(mail)

Catch ex As Exception

‘If errors
Throw New System.Exception(ex.Message, ex.InnerException)

End Try

‘Cleaning up
smtp = Nothing
mail.Dispose()
mail =
Nothing

End Sub

Thats it. Read more about system.net.mail here.

Leave a Comment