vb.NET Email Code Example

Visual Studio LogoIf there is one thing that burns me, it’s code examples that don’t work. I recently stumbled across some broken code for vb.NET to sends emails. Look, I know this example is from 2003, but if people are going to comment suggestions on how to make your example code work, the least you can do is update it. Also, it irks me that this page was #1 on Google when I searched for it. Below is a slightly simpler example of vb.NET to send an email, that WORKS.

' Basic Function for Sending Email in VB.NET
' Ben Liyanage
' http://perfectresolution.com/?p=129 

Imports System.Net.Mail
Public Shared Sub SendMail( _
    ByVal strFrom As String, _
    ByVal strTo As String, _
    ByVal strSubject As String, _
    ByVal strBody As String, _
    ByVal strSMTPServer As String)

    ' Create a MailMessage Object, which stores information about our email.
    Dim email As New MailMessage()

    ' Assign Various properties to our email.
    With email
        ' The email address of the person who will be sending this email.
        .From = New MailAddress(strFrom)

        ' The email addresses of people who will recieve this email.
        ' Note that the 'To' propterties is a collection, 
        ' so you can store multiple email addresses in it.

        ' The subject of your email.
        .Subject = strSubject

        ' The content of the email.
        .Body = strBody
    End With

    ' Establish a connection to the SMTP mail server.
    Dim mailConnection As New SmtpClient(strSMTPServer)

    ' Send our email with the SMTP mail server.

End Sub

There are more options out there (cc, bcc, attachments), but honestly you don’t need these a lot unless you are building out a full email client.

One Response to “vb.NET Email Code Example”

  1. Isiah - February 19, 2015

    Want to copy posts from other websites rewrite them in seconds and
    post on your page, or use for contextual backlinks? You
    can save a lot of writing work, just type in gogle:

    Daradess’s Rewriter

Leave a Reply