How to send mail in asp.net using gmail smtp server

  • Facebook
  • Twitter
  • Delicious
  • StumbleUpon
  • Pinterest
  • Google Plus

An simple method to send mail in asp.net using your own gmail account. Gmail provides you SMTP and POP access to sending and receiving mails. If you are not having smtp server to send mails than gmail is a good solution to send mail using Asp.net application.

First Thing we have to do is declare a namespace System.Web.Mail. To create a mail object, you need to create an instance of MailMessage. MailMessage contains properties such as To, Subject, BCC, CC etc. After that you have to set authentication, port, username and password. Another important thing is to run STARTTLS. STARTTLS is a command to initiate SSL handshake and switch to protection mode.


Namespace for sending mail in .NET using gmail.com

<%@ Import Namespace="System.Web.Mail" %>

Here comes the example for sending mail in asp.net using gmail

<script language="c#" runat="server">

 public void Page_Load(object sender, EventArgs e)
    {
         try
              {
		  MailMessage mail = new MailMessage();
                  mail.To = "sample@tomail.com";
                  mail.From = "sample@frommail.com";
                  mail.Subject = "Test Mail.";
                  mail.Body = "Body Message";

                  //For  authentication
             
                  mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); 
                  
                  //Set Your Gmail USer Name   

                  mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "test@gmail.com");
  
                  //set your password here    
                  mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "password");    
    
                  // Default Port Numer Dont change it
                  mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", 25);
                  
                  // STARTTLS 
                  mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", true);

                  SmtpMail.SmtpServer = "smtp.gmail.com";
             
                  SmtpMail.Send( mail );
                 
                   Response.Write("your message has been sent successfully"); 
			  
	       }

               catch (Exception ex)
               {

               } 
    }

</script>

Above example must work in both local and also in server without any access problem and issues. Especially with GoDaddy server.

Like(0)Dislike(0)

Share and Enjoy

rathnakumaravel@yahoo.com'

Rathna

I m Rathina kumaravel (Ramki) and i m a software Engineer in Chennai. I have achieved Bachelor of engineering in Computer Science. Iā€™m a simple person who hides a thousand feelings behind the happiest smile.

Leave a Reply