How to send email using VB.NET code

By: Issac Emailed: 1674 times Printed: 2157 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Surprised, we can use SMTP protocol and .net source code for sending an email, SMTP stands for Simple Mail Transfer Protocol, in VB.NET we can use System.Net.Mail namespace for send mail. We can instantiate SmtpClient class and assign the Host and Port. The default port using SMTP is 25, but it may vary different Mail Servers. The following example shows how to send emails from a Gmail address.

The Gmail SMTP server name is smtp.gmail.com and the port using send mail is 587. Here using NetworkCredential for password based authentication.

Imports System.Net.Mail
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
        Try
            Dim SmtpServer As New SmtpClient()
            Dim mail As New MailMessage()
            SmtpServer.Credentials = New _
		Net.NetworkCredential("username@gmail.com", "password")
            SmtpServer.Port = 587
            SmtpServer.Host = "smtp.gmail.com"
            mail = New MailMessage()
            mail.From = New MailAddress("YOURusername@gmail.com")
            mail.To.Add("TOADDRESS")
            mail.Subject = "Test Mail"
            mail.Body = "This is for testing SMTP mail from GMAIL"
            SmtpServer.Send(mail)
            MsgBox("mail send")
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
End Class

You have to provide the informations like your gmail username and password , and the to address also.


VB.net Home | All VB.net Tutorials | Latest VB.net Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(7)


1. View Comment

It won't work for me ;S

View Tutorial          By: jordi at 2011-01-21 08:22:45
2. View Comment

I get an error returned saying the SMPT server requires a secure connection - how do I do this?

View Tutorial          By: Christian Peut at 2011-04-04 04:35:51
3. View Comment

Imports System.Web
Imports System.Net.Mail
Imports System.Text
Imports System.Web.Mail
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim myMessage As New System.Web.Mail.MailMessage
TxtSendTo.Focus()
End Sub
Public Sub SendMailMultipleAttachments(ByVal From As String, _
ByVal sendTo As String, ByVal Subject As String, ByVal Body As String, Optional ByVal AttachmentFiles As ArrayList = Nothing, Optional ByVal CC As String = "", Optional ByVal BCC As String = "", Optional ByVal SMTPServer As String = "")
Dim i, iCnt As Integer
Dim myMessage As New System.Web.Mail.MailMessage
Try
With myMessage
.To = sendTo
.From = From
.Subject = Subject
.Body = Body
.BodyFormat = System.Web.Mail.MailFormat.Text
'CAN USER MAILFORMAT.HTML if you prefer

If CC <> "" Then .Cc = CC
If BCC <> "" Then .Bcc = BCC
If Not AttachmentFiles Is Nothing Then
iCnt = AttachmentFiles.Count - 1
For i = 0 To iCnt
If FileExists(AttachmentFiles(i)) Then _
.Attachments.Add(AttachmentFiles(i))
Next
End If
End With
If SMTPServer <> "" Then _
'System.Web.Mail.SmtpMail.SmtpServer = "mail.mavensystems.biz"
System.Web.Mail.SmtpMail.SmtpServer = "smtp.comcast.net"
End If
System.Web.Mail.SmtpMail.Send(myMessage)
Catch myexp As Exception
MsgBox(myexp.Message, MsgBoxStyle.Critical, Me.Text)
End Try
End Sub

Private Function FileExists(ByVal FileFullPath As String) _
As Boolean
If Trim(FileFullPath) = "" Then Return False
Dim f As New IO.FileInfo(FileFullPath)
Return f.Exists
End Function

'Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
' With odlgAttachment
' .InitialDirectory = "C:\"
' .Filter = "All Files (*.*)|*.*|HTML Files (*.htm;*.html)|*.htm|Microsoft Mail Documents (*.msg)|*.msg|Word Documents (*.doc)|*.doc|Excel Files(*.xl*)|*.xl*|Excel Worksheets (*.xls)|*.xls|Excel Charts (*.xlc)|*.xlc|PowerPoint Presentations (*.ppt)|*.ppt|Text Files (*.txt)|*.txt"
' .FilterIndex = 1

' The OpenFileDialog control only has an Open button, not an OK button.
' However, there is no DialogResult.Open enum so use DialogResult.OK.
' If .ShowDialog() = DialogResult.OK Then
' Dim fname As String
' fname = .FileName
' myMessage.Attachments.Add(New System.Web.Mail.MailAttachment(fname))
' Dim strFileName() As String = .FileName.Split(New Char() {CChar("\")})
' strFileName.Reverse(strFileName)
' lblfile.Text = lblfile.Text & strFileName(0) & ","
' End If
' End With
'End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Call SendMailMultipleAttachments(TxtFrom.Text, TxtSendTo.Text, TxtSub.Text, TxtBody.Text, , TxtCc.Text, TxtBcc.Text)
MsgBox("Your Messege Be Sent", MsgBoxStyle.Information, "Messege Sent")
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Close()
End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
'TxtFrom.Clear()
TxtSendTo.Clear()
TxtSub.Clear()
TxtBody.Clear()
TxtCc.Clear()
TxtBcc.Clear()
'lblfile.Clear()
TxtSendTo.Focus()
End Sub

'Private Sub Btn_Attach_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Attach.Click
' Dim myMessage As New System.Web.Mail.MailMessage
' With odlgAttachment
' .InitialDirectory = "C:\"
' .Filter = "All Files (*.*)|*.*|HTML Files (*.htm;*.html)|*.htm|Microsoft Mail Documents (*.msg)|*.msg|Word Documents (*.doc)|*.doc|Excel Files(*.xl*)|*.xl*|Excel Worksheets (*.xls)|*.xls|Excel Charts (*.xlc)|*.xlc|PowerPoint Presentations (*.ppt)|*.ppt|Text Files (*.txt)|*.txt"
' .FilterIndex = 1

' ' The OpenFileDialog control only has an Open button, not an OK button.
' ' However, there is no DialogResult.Open enum so use DialogResult.OK.
' If .ShowDialog() = Windows.Forms.DialogResult.OK Then
' If IsNothing(TxtAttach) Then

' ' Clear the "(No Attachments)" default text in the ListView
' TxtAttach.Clear()
' End If
' 'TxtAttach.Add(New Attachment(.FileName))

' ' You only want to show the file name. The OpenFileDialog.FileName
' ' property contains the full path. So Split the path and reverse it
' ' to grab the first string in the array, which is just the FileName.
' Dim strFileName() As String = .FileName.Split(New Char() {CChar("\")})
' System.Array.Reverse(strFileName)
' 'TxtAttach.strFileName(0)
' End If
' End With

'End Sub
End Class


View Tutorial          By: Naresh at 2011-05-24 07:27:12
4. View Comment

"I get an error returned saying the SMPT server requires a secure connection - how do I do this?"

SmtpServer.EnableSsl = True


View Tutorial          By: Dennis at 2011-06-24 10:18:10
5. View Comment

how about if you attach microsoft word documents?plz help..

View Tutorial          By: gian at 2012-01-06 03:11:44
6. View Comment

i cannot add attachment
its saying
"Exceed storage allocation. The sever response was 5.7.0 our system detected an illegal attachment on your message"


View Tutorial          By: Rintu Das at 2012-05-04 18:07:48
7. View Comment

Very nice tutorial. Hi Rintu for attachment u can visit
http://ram-a-singh.blogspot.in/2013/03/how-to-send-email-with-attachment-vbnet.html


View Tutorial          By: ras at 2013-03-14 17:19:47

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Issac
Save/Write/Read image file from/to a database using Java program
How to modify the objects using java classes
Java program for Cloning
Java program for changeable wrapper class
A tutorial on Chat Server and Chat Client in VB.net
Chat Server in VB.net
Chat client in VB.net
How to open and read an XML file in VB.net
How to create an XML file in VB.net
XML and VB.net
How to create an XML file in VB.NET using Dataset
Multi Threaded Client Socket Programming in VB.net
Multi Threaded Server Socket Programming in VB.net
Multi threaded Socket Programming in VB.net
Client Socket Program sample in VB.net

More Tutorials in VB.net
Scope in VB.net
Unstructured Exception Handling in VB.net
Structured Exception Handling in VB.net
Creating Sub Procedures in VB.net
Creating Functions in VB.net
Passing a Variable Number of Arguments to Procedures in VB.net
Specifying Optional Arguments with default values in Procedures in VB.net
Preserving a Variable's Values between Procedure Calls in VB.net
Procedure Delegates in VB.net
Properties in VB.net
Understanding Scope in VB.net
Using Resume Next and Resume Line in VB.net
Using On Error GoTo 0 in VB.net
Getting an Exception's Number and Description in VB.net
Raising an Exception Intentionally in VB.net

More Latest News
Most Viewed Articles (in VB.net )
Your first VB.NET Crystal Reports - A step by step guide
Arrays and Dynamic Arrays in VB.net
DataRow Class in VB.net
Using the ServiceBase Class in VB.net
Using Resume Next and Resume Line in VB.net
File Extensions Used in VB .NET
Operators in VB.net
Do Loop in VB.net
For Each…Next Loop in VB.net
Sub Procedures and Functions in VB.net
How to send email using VB.NET code
A tutorial on Chat Server and Chat Client in VB.net
Handling Timer Events - and Creating an Alarm Clock in VB.net
Creating Context Menus in Code using VB.net
Using the EventLog Class in VB.net
Most Emailed Articles (in VB.net)
Send SMS using VB code
String equals, Copy to & Copy to in VB.net
How to export from database to excel using VB.net
A tutorial on Chat Server and Chat Client in VB.net
String.Contains (), compare, clone in VB.net
Your first VB.NET Crystal Reports - A step by step guide
Using a Web Service in VB.net
Using Excel 2007 Chart in VB.NET 2005
How to export from DataGridView to excel using VB.net
Socket Programming in VB.net
Handling Timer Events - and Creating an Alarm Clock in VB.net
Using Resume Next and Resume Line in VB.net
File Extensions Used in VB .NET
Using Select Case in VB.net
For Loop in VB.net