Thursday, November 4, 2010

Send mail in asp.net

Sending automated mails is very important for almost any web site. It can be used for newsletters or a simple contact us page. In this example i will make a contact us page and send information over an smtp server.
I will be using google's smtp server known as: smtp.google.com because its free. You need to have a gmail account for this.

Now lets check out the page layout:

Now the code:


using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
string mail_to = "viper_451@yahoo.com";
string mail_from = "fareedahmed512@gmail.com";
System.Net.Mail.MailMessage mail = new MailMessage(); //initiate
mail.To.Add(mail_to);
mail.From = new MailAddress(mail_from,"WEBMASTER",System.Text.Encoding.UTF8);
mail.Subject = "Mail from client";
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = "Name: " + TextBox1.Text + " ||Email: " + TextBox2.Text + " ||Comments: " + TextBox3.Text;
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true;

mail.Priority = MailPriority.High;

///////Working on smtp client:::::

SmtpClient cl = new SmtpClient();

cl.Credentials = new System.Net.NetworkCredential(mail_from,"Your_password_here");
cl.Port = 587; // gmail uses this port
cl.Host = "smtp.gmail.com";
cl.EnableSsl = true;

try
{
cl.Send(mail);
Response.Write("Thank you!!");
}

catch(Exception exp) {
Response.Write("Sorry try again :(");

   }
  }
}

--------------------------------END OF CODE--------------------------------------

 

4 comments:

  1. Thanks so much for ur code buddy :)it was really help full.
    if u find some free time can u explain me this code with comments and send it to ops_apeiron@hotmail.com

    ReplyDelete
  2. hi i'm getting error like "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required"

    ReplyDelete