Free Information Technology Magazines and eBooks

Saturday, October 10, 2009

How to send email via Gmail SMTP in VB.NET

Before, I already discussed how to send email in VB.NET using SmtpClient class of System.Net.Mail namespace and todays topic is no different except that it will specifically use Gmail Smtp mail server. Of course you need to have a GMail account first to be able to use this code.



1. Create a new VB.NET Project. On your default form, include the following namespaces.


Imports System.Net.Mail


2. Copy and paste the following code on your send email button.


Dim UserName as String = "sample@gmail.com"
Dim mail As MailMessage = New MailMessage
Dim attach As New Attachment(FilePath)


mail.From = New MailAddress(UserName)
mail.To.Add(New MailAddress(UserName))
mail.Subject = Subject
mail.Body = "This is a test message from fryan0911.com"
If FilePath <> " then" Then
mail.Attachments.Add(attach)
End If

mail.IsBodyHtml = True

Dim client As SmtpClient = New SmtpClient("smtp.gmail.com", 587)
client.EnableSsl = True
client.Credentials = New System.Net.NetworkCredential(UserName, Password)
Try
client.Send(mail)
Catch ex As Exception
MessageBox.Show("Sending email failed. Please Try again")
End Try

You can tweak the above code for your need.

For more VB.NET coding tips & tricks, subscribe now.

3 comments:

Anonymous said...

hii, i hed created one listview there is three column naimly id,name price. i can successfully insert the data in listview through a 3 textbox. but problem is how can i add all the rows of 3 column to a total. and how to insert the this data in database using vb.net. i had succssfully done in vb6 but in vb.net it not work. please help me it's my school project. thank you send me code on my mail id pritesh_271187@yahoo.co.in

Anonymous said...

hii, this is a code of finding the name which you have typed in textbox and it will find in the list box. if there is name it then focus on that name of the list otherwise not. i want to convert in vb.net but in vb.net it gives me error at left function which tell me taht not t insert a index. so how to do that. please help me send me on my mail. pritesh_271187@yahoo.co.in

thank you.

Dim a As Integer
Dim b As Boolean
Do While Not b And a < cmbcust.ListCount
If UCase(Left(cmbcust.List(a), Len(txtname.Text))) = UCase(txtname.Text) Then
cmbcust.ListIndex = a
b = True
End If
a = a + 1
Loop

Anonymous said...

I am try,

It not work

Can you find new solution?

thank.