Send Email using Gmail SMTP

On September 27, 2009, in .NET, by Vaibhav

In one of my Application called Exxecutive (secret !) I wanted to send email to my clients using my Gmail Account. I wanted to make sure Gmail keeps a copy of my sent emails. If I use SMTP provided by Microsoft IIS, Gmail doesn’t come in the picture. After doing some research I wrote a function that will use Gmail’s SMTP server and send email and also keep a copy in the send mail folder. This function uses .NET’s Mail Namespace.

It is important to note here that Gmail uses port 587 (a new preferred port for mail submission) and SSL

Here is the VB.net code:

    Function SendEmail(ByVal inTo As String, ByVal inSubject As String, ByVal inBody As String)
        Try
            Dim MySmtpClient As New System.Net.Mail.SmtpClient()
            Dim MyCredentials As New System.Net.NetworkCredential
 
            MyCredentials.UserName = "name@gmail.com"
            MyCredentials.Password = "***your password here****"
 
            MySmtpClient.Host = "smtp.gmail.com"
            MySmtpClient.Port = 587 ' 25
            MySmtpClient.Credentials = MyCredentials
            MySmtpClient.EnableSsl = True
            Dim ToMailAddress As New MailAddress(inTo)
            Dim FromMailAddress As New MailAddress(MyEmailAddress, MyEmailDisplayName)
            Dim MyMailMessage As New System.Net.Mail.MailMessage(FromMailAddress, ToMailAddress)
 
            MyMailMessage.Subject = inSubject
            MyMailMessage.Body = inBody
            MyMailMessage.IsBodyHtml = True
            MySmtpClient.Send(MyMailMessage)
            Return True
        Catch ex As Exception
            MsgBox(ex.ToString)
            Return False
        End Try
    End Function
 

1 Response » to “Send Email using Gmail SMTP”

  1. Chinmay Shah says:

    Hey, sounds good man!

Leave a Reply