Sending Mail from ASP.NET Webpage using VB.Net


Before we start follow this steps to send the mail. First we need to import the System.Web.Mail namespace in the ASP.NET Web page in order to utilize the methods and properties.

Syntax:-

Import the Namespace

<% @Import Namespace="System.Web.Mail" %>

Now we are going to start with the actual utilization of the System.Web.Mail namespace.

Creating a MailMessage

The MailMessage class contains properties like :- To, From, Cc, Bcc, BodyFormat, Subject, Priority, Body, etc. So, to send an email, we should create an instance of  the MailMessage class and set its properties. The following code will explain how to create an instance and set the property of MailMessage class.

'Creating an instance of the MailMessage class
Dim objMailMessage As New MailMessage
'Setting the properties
objMailMessage.To = "[email protected]" 'E.g :[email protected]
objMailMessage.From = "[email protected]" 'E.g :[email protected]
'If you want to send the CC to someone else...
objMailMessage.Cc = [email protected]
'If you want to send the BCC this email to someone else...
objMailMessage.Bcc = [email protected]
'Sending the email in text format
' If you want to send the mail in Html format then we need to change the code like :-" MailFormat.Text to MailFormat.Html "
objMailMessage.BodyFormat = MailFormat.Text
'Setting the priority - For priority 3 options are available which are Normal,Low and High
objMailMessage.Priority = MailPriority.Normal
'Setting the subject
objMailMessage.Subject = "Test Mail"
'Setting the body
objMailMessage.Body = "Hi! This is a test mail"

Sending the MailMessage

Once we have created a instance of MailMessage class with correct properties setting. We simply need to call the static Send method of the SmtpMail class, passing in the MailMessage class instance:

'Now, to send the message, we will use the Send method of the SmtpMail class
SmtpMail.Send(objMailMessage)

By using the Send method above, the local SMTP server is used to send the email message.

Note:- In order to specify a different SMTP mail server to use to send the message, set the SmtpServer property:

SmtpMail.SmtpServer = EmailServerName 

Because SmtpMail class uses the inbuilt SMTP Service  of Windows 2000 to do the work of actually sending the email message.

Up Next
    Ebook Download
    View all
    Learn
    View all