Tuesday, April 10, 2012

Send Mail using VB.NET

In VB.NET you use SMTP protocol for sending email . SMTP stands for Simple Mail Transfer Protocol . VB.NET uses System.Net.Mail namespace for sending mail . You need to instantiate SmtpClient class and assign values to the Host and Port. For SMTP default port is 25 and it can vary for different Mail Servers. In the following example I have used Gmail address to send mail

The Gmail SMTP server name is smtp.gmail.com and the port using send mail is 587.

Design:

Code:

Imports System.Net.Mail

Public Class Form1
    Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.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("username@gmail.com")
            mail.To.Add(txtTo.Text)
            mail.Subject = txtsubject.Text
            mail.Body = txtmail.Text
            SmtpServer.Send(mail)
            MsgBox("Mail send!")
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
End Class

No comments:

Post a Comment