How to Send Email from VB.NET | Source Code

In Microsoft Visual Basic .Net, We can send email by using SMTP Protocol. SMTP stands for Simple Mail Transfer Protocol. It need System.Net.Mail namespace.

Here, We are going to use Gmail SMTP server to send email. The Gmail SMTP server name is smtp.gmail.com and port is 587. This may vary for different SMTP Mail server.


The following vb.net simple program shows how to send emails from a Gmail address.

Code
Imports System.Net.Mail

Public Class Form1

    Private Sub butsend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles butsend.Click

        Dim mail As New MailMessage
        mail.To.Add(tbto.Text & "@gmail.com") ' To address
        mail.From = New MailAddress(tbuser.Text & "@gmail.com") ' From address
        mail.Subject = tbsubject.Text ' Mail Subject
        mail.Body = tbbody.Text ' Mail Body text

        Try

            Dim smtp As New SmtpClient("smtp.gmail.com") ' Gmail Smpt Client
            smtp.EnableSsl = True ' Enable SSl
            smtp.Credentials = New System.Net.NetworkCredential(tbuser.Text & "@gmail.com", tbpass.Text) ' Sender email address and Password
            smtp.Port = "587" ' Gmail Port number
            smtp.Timeout = 20000 ' Set time out
            smtp.Send(mail)
            MessageBox.Show("Successfully Mail Sent.")

        Catch ex As Exception

            MessageBox.Show(ex.Message)

        End Try    
    
    End Sub

End Class

Source Code

You can download source code for this simple vb.net program for sending emails from gmail.




Screenshot

How to Send Email from VB.NET

1 comment:

  1. 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

    ReplyDelete