Using System.Net.Mail namespace to send email

Here’s a little demo of how to use the System.Net.Mail namespace to have your application automatically send an email. This sample is a class method that sends an email notification to the developer/webmaster/website owner/whoever when a new user registers on the site.

First, some set up. I keep the values for the From email address and the host IP address in the appSettings section of the web.config file. To retrieve them, I have a couple shared ReadOnly properties in my class, like so:

Public Shared ReadOnly Property Host() As String
Get
Return System.Configuration.ConfigurationManager.AppSettings("Host").ToString
End Get
End Property

Public Shared ReadOnly Property FromAddress() As String
Get
Return System.Configuration.ConfigurationManager.AppSettings("From").ToString
End Get
End Property

Now that I can easily get to these settings, I build my method, as below:

”’ <summary>
”’ Send email notification when a new user registers
”’ </summary>
”’ <param name=”ToAddress”>System.String containing the email
”’ address that the message should go to
”’ </param>
Public Shared Sub NotifyEmail(ByVal ToAddress As String)

Try

‘instantiate new MailMessage object and pass in from and to
’email addresses (FromAddress is a readonly property pulling from
‘web.config file)
Using message As New System.Net.Mail.MailMessage(FromAddress, ToAddress)

‘set rest of message properties
message.Subject = "New User"
message.IsBodyHtml = True
‘set to true if you want to use html in body
message.Body = "A new user has registered"

‘instantiate new SmtpClient object and pass in host information
‘(Host is a readonly property pulling from web.config file)
Dim smtp As New System.Net.Mail.SmtpClient(Host)

‘send message
smtp.Send(message)

‘dispose of MailMessage object
End Using

Finally

‘dispose of SmtpClient object
smtp = Nothing

End Try

End Sub

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s