Saturday, February 14, 2015

How to Send Email Using VB Net

Sending and receiving emails has now became an important task in our daily life. Email service providers such as Hotmail, Gmail & Yahoo have provided their SMTP Ports so that third party developers can use them in their applications.

In visual basic.net we use SMTP i.e Simple Mail Transfer Protocal which help us in composing electronic mails and send them to various sources.

Also Read: SQL Injection Attacks - How to Prevent VB.Net Database Applications


How to Send Email Using VB.Net

We need to import the following namespace “Imports System.Net.Mail” in order to use the SMTP class.

About System.Net.Mail Namespace

This Namespace provides various list of classes that help us to create, send, receive and do many other email related tasks.

You can get a more detailed information from the Microsoft Developer Network’s website http://msdn.microsoft.com/en-us/library/system.net.mail(v=vs.110).aspx

How to Send Email Using VB.Net

I’ll demonstrate a simple example that allow us to send emails in vb.net:

1. Create a new windows form application project in visual basic.net.

2. Add three labels and three textboxes and name them as given below:

Label1  -  To
Label2  -  Subject
Label3  -  Body

3. Add a button and change its text to Send.


How to Send Email Using VB.Net

4. Double click button to switch to code view and paste the code given below.

Dim MyMailMessage As New MailMessage()
Try
MyMailMessage.From = New MailAddress("youremail")
MyMailMessage.To.Add(TextBox1.Text)
MyMailMessage.Subject = TextBox2.Text
MyMailMessage.Body = TextBox3.Text
Dim SMTP As New SmtpClient("smtp.gmail.com")
SMTP.Port = 587
SMTP.EnableSsl = True
SMTP.Credentials = New System.Net.NetworkCredential("youremail", "yourpassword")
SMTP.Send(MyMailMessage)
MsgBox("Your Mail has been Successfully sent")
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox1.Focus()
Catch ex As Exception
MsgBox(ex.ToString)
End Try

5. Change youremail with your current email address and yourpassword with your email ID’s password. Don’t forget to import the following namespace: Imports System.Net.Mail 

That’s it!! Run your Project and send a test email.

Note: It works only with Gmail Account because we have used Gmail’s SMTP Port.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.