Jump to content

Creating a contact form - ASP.NET (C#)

0
  Ángel Manuel García Carmona's Photo
Posted Jan 03 2011 07:13 AM

There, i'm going to explain how to create a contact form in an ASP.NET website, in this case, written in C#.

First, you must insert some textboxes which will be the characters to fill (email, name, message, etc.) and a button which will be used to send the message. Once that those elements are inserted, you must add in the code (in the event handler of the button -click-) a MailMessage object and its properties (To, From, etc.) and when that object and its properties are established, the message is sent through the Send method of SmtpClient.


protected void Button1_Click(object sender, EventArgs e)
    {
       string mail = "myaddress@example.es";
            MailMessage email = new MailMessage(EmailTB.Text, mail);
            email.From = new MailAddress(EmailTB.Text, FNameTB.Text + " " + LNameTB.Text);
            email.Body = CommentsTB.Text; // The message's content
            SmtpClient client = new SmtpClient();
            // These are the properties of the SMTP client
            client.Host = "smtp.example.es"; 
            client.Port = 00;
            client.Credentials = new NetworkCredential(mail, "password"); // Credentials of the address where the mail will be sent.
            client.EnableSsl = true;

            client.Send(email); // Method which the mail is sent
    }

The SMTP server properties can be also established in the web.config file.
[/font]
<system.net>
  <mailSettings>
    <smtp>
      <network enableSsl="true"
           host="smtp.example.es"
           port="0000"
           userName="username@example.com"
           password="password" />
    </smtp>
  </mailSettings>
</system.net>

By these steps, you can have built your contact form.

Tags:
0 Subscribe


0 Replies