Here is another quick example of how to send an email from a web page, this time using ASP.NET 2. (for ASP.NET 1.1, click here) The code for the ASP.NET 1.1 technique needs to be refactored to be used in ASP.NET 2.0 since the System.Web.Mail.MailMessage and System.Web.Mail.SmtpMail classes become obsolete in .NET 2. Instead, there are now the System.Net.Mail.MailMessage and System.Net.Mail.SmtpClient classes, as shown below:


    1         protected void btnSend_Click(object sender, EventArgs e)

    2         {

    3             //Assuming the required fields have been validated using a validator ...


    5             MailMessage msg = new MailMessage();

    6             msg.From = new MailAddress(txtFrom.Text);    //you can also add a From Name for display purposes

    7             msg.To.Add(txtTo.Text);                      //you can also add a To Name for display purposes

    8             if (txtCc.Text.Length > 0)

    9                 msg.CC.Add(txtCc.Text);                  //you can also add a CC Name for display purposes

   10             if (txtBcc.Text.Length > 0)

   11                 msg.Bcc.Add(txtBcc.Text);                //you can also add a Bcc Name for display purposes

   12             msg.Subject = txtSubject.Text;

   13             msg.Body = txtBody.Text;


   15             SmtpClient smtp = new SmtpClient(txtSMTPServer.Text);

   16             smtp.Send(msg);

   17         }