In visual basic.net we use SMTP i.e Simple Mail Transfer Protocol which helps us in composing electronic mails and sending them to various sources.
Also Read: SQL Injection Attacks – How to Prevent VB.Net Database Applications
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 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 allows 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.
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.
kindly help me!
if{there is internet connection} then
this code works
otherwise not
because i want to use this code in Library Management System,email will be send on each issue & return of book to the particular student.
Sometimes there is no internet connection so there will be error .
I have been used this code in Visual Studeo 2015 with sucess. but whwn I make a new projekt in Visual Studeo 2017 it fails with the line
SMTP.Credentials = New System.Net.NetworkCredential(“youremail”, “yourpassword”)
as lon this line is in the code the project will not start
its not working if i test it it says: 5.5.1 authentication needed. (server response)
I am using VS2012. when I run the project the following message appears” Systems.FormatException: the specifies string is not the form required for an email address at the System.NetMail.MailAddressParse.ReadcfwsAndTrowfIncomplete(string data,int32 index)
the sentence ends vy line8 that is “MyMailMessage.To.Add(TextBox1.Text)”
Golden, thanks for sharing