Monday, 1 April 2013

Sending E-mail using ASP.net through Gmail account (Gmail SMTP Server account)


Sending E-mail using ASP.net through Gmail account (Gmail SMTP Server account)


Sending mail in day to day life is a basic task of web application for many purpose like- error logging, reporting, performance   alerting as well as many other reasons. 

If you have taken web space somewhere on a web server then you are provided with the Email accounts and SMTP and POP services for sending and receiving E-mails. Sometimes you don't have SMTP server accounts and you may want to send email. Or sometimes, for other reasons also you may want to use third-party SMTP sever for sending E-mails.
Gmail is a good solution for us to solve this purpose. Gmail provides SMTP and POP access which can be utilized for sending and receiving E-mails.

In this tutorial I am going to introduce how to use a Gmail account to send email by SMTP.

Step 1:Create a New Website in visual studio and add web form to it. And design it.

Step 2: Write following code to the send button click event.
protected void btnSendMail_Click(object sender, ImageClickEventArgs e)
    {
        try
        {


            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
            string from = "skbadliya@gmail.com";

            mail.To.Add(txtTo.Text.Trim());
            mail.From = new System.Net.Mail.MailAddress(from);

            mail.Subject = txtSubject.Text;          
            mail.Body  =txtBody.Text;
            mail.IsBodyHtml = true;
        

            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
            client.Host = "smtp.gmail.com";
            client.EnableSsl = true;//Gmail works on Server Secured Layer
            //Add the Creddentials- use your own email id and password
            System.Net.NetworkCredential networkcred = new System.Net.NetworkCredential();
            networkcred.UserName = from;
            networkcred.Password = "yourpassword";
            client.Port = 587;// Gmail works on this port
            client.Credentials = networkcred;
            client.Send(mail);
            lblMsg.Text = "Mail Send Successfully...";

        }
        catch(Exception ex)
        {

            lblMsg.Text = ex.Message;
        }
    }



You can download complete code from here:

No comments:

Post a Comment