Thursday, October 16, 2014

Send Email using ASP.NET with C# with SMTP gmail Server

  • Create new ASP.NET website with simple design as follows 
    • Four Lables : lblName, lblEmail, lblKey, lblComment
    • Four Textboxes : txtName,  txtEmail, txtKey and txtComment
    • A button : btnSubmit
        The design would look as below. (In this design  TextBoxWatermarkExtender is used )



  • Add a class 'clsSend_Email' to your website code as follows

using System.Net.Mail;

public class clsSend_Email
{
     public clsSend_Email()
     {
     }

    public string Send_Email(string ToMail,string fromMail,string  
    SubjectMail,string BodyMail)
    {
        try
        {

            MailMessage mmSubmit = new MailMessage();
            mmSubmit.To.Add(ToMail);

            MailAddress maFrom = new MailAddress(fromMail);
            mmSubmit.From = maFrom;
           
            mmSubmit.Subject = SubjectMail;
            mmSubmit.Priority = MailPriority.Normal;
            mmSubmit.Body = BodyMail;
           
            SmtpClient sc = new SmtpClient("smtp.gmail.com", 587);
            //we will send email using gmail smtp server

            sc.Credentials = new System.Net.NetworkCredential("loginid",             "password");
                       
            //   loginid and password would be login id and password
            //   for your gmail account (from Email)
            sc.EnableSsl = true;
            sc.Send(mmSubmit); 
            return string.Empty;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
   
    }
}




  • On button click event of submit button, call Send_Email method from class clsSend_Email
protected void btnSubmit_Click(object sender, EventArgs e)
    {
        //Send Email
        try
        {
            clsSend_Email email = new clsSend_Email();
            string Subject="New Email from "+txtName.Text+" regarding "+txtKey.Text.Trim()+
            EmailID : "+txtEmail.Text.Trim();
            string mailStatus= email.Send_Email("From Email ID here ",                
            txtEmail.Text.Trim(),Subject,txtComment.Text.Trim());

            if (mailStatus == string.Empty)
            {
                lblErrMSG.Text = "Thank You for your response!";
            }
            else
            {
                lblErrMSG.Text = mailStatus;
            }
        }
        catch (Exception ex)
        {
           
            lblErrMSG.Text = ex.Message;
        }
       
    }


  • Run and Execute application

1 comment:

  1. The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

    Sometime you may get this error.
    to avoid such error go to the link https://www.google.com/settings/security/lesssecureapps and turn on feature access for less secure app

    ReplyDelete