Code Sample: VB.NET SMTP Mail function

1. Create a Visual Basic Class for your project by right clicking the project and select add.


2. Change the language to Visual Basic and select Class from the list of Installed Templates.


3. Name the class clsNotify. Add the code below to the class.(You can name it whatever you want really, but you’ll need to change Public Class definition in the code below. Your reference to class will also need to change.)

Imports Microsoft.VisualBasic

Imports System.Net.Mail 'Add reference to Mail Class

Public Class clsNotify 'Create a class that can be called from anywhere within your application

Shared Sub SendEmail(ByVal strTo As String, ByVal strSubject As String, ByVal strBody As String, ByVal strFrom As String, Optional ByVal blnHTML As Boolean = True) 'Create Subroutine that can have parameters passed to it

Dim mailmsg As New System.Net.Mail.MailMessage 'Declare Mail message variable

Dim mailfrom As New System.Net.Mail.MailAddress(strFrom) 'Declare Mail Message Address, references strFrom passed from Sub

Dim mailcred As New System.Net.Mail.SmtpClient 'Declare SMTP Client to pass credentials through

Dim strRecipients() As String = strTo.Trim.Replace(" ", "").ToString.Split(";") 'Replace spaces and blanks with Semi Colon to deliniate recipiants addresses

Dim smtpuser As New System.Net.NetworkCredential("MyLogin", "MyPassword") 'define SMTP user credentials

mailmsg.To.Add(strRecipients(0)) 'Add Recipiants to MailMsg Variable

mailmsg.IsBodyHtml = blnHTML 'Add HTML or just text for Email Body

mailmsg.From = mailfrom 'Add Email from line, Can be anything really

mailmsg.Subject = strSubject 'Add Subjec to mail Line

mailmsg.Body = strBody 'Add Body as plain text incase users mail app doesn't support HTML mail

mailmsg.Priority = MailPriority.High 'Set Priority if Desired

Dim smtp As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient 'Declare SMTP Mail Client

smtp.Host = "MyServer" 'Set SMTP Mail Server

smtp.Credentials = smtpuser 'Set Authenticate Credentials for Server

Try 'Create try catch incase we got something wrong, prevents code from throwing an exception

smtp.Send(mailmsg) 'Call SMTP.SEND and reference MailMSG Variable. Mail should send at this point

Catch ex As Exception

'ex.Message, If you tie ex.message can be tied to a control to display if for some reason the mail fails to send

End Try

End Sub

End Class


After you have added the code to the class and saved it. You can simply reference the Mail class from anywhere within your code.

clsNotify.SendEmail("RecipiantsAddress", "Subject", "EmailBody", "FromAddress", True)



About the author

Leave a Reply