HTML Code for Email Form

email form sampleAny serious business website should have a way for the users to reach you. Displaying your email address and phone number is one method. However, both of them requires the user to fire up the email client or phone to reach you. How about having a quick contact form ? The user just have to click a link and enter their question.

Sample Email Form Code

Here are some sample email form code that you can just plug in to your website and have a quick email form.

Getting the form to work

Sending an email from an HTML form requires that the form submits a number of necessary pieces of information (usually the email address from which the email is sent, the email address to which the email is sent, the email’s subject and the email message itself) to a server-side script capable of sending the email through an SMTP mail server:

HTML Form Code

<form action="ServerScript.php" method="POST">
<label for="from">From:</label>
<input type="text" name="from"/>
<label for="to">To:</label>
<input type="text" name="to"/>
<label for="subject">Subject:</label>
<input type="text" name="subject"/>
<label for="message">Message:</label>
<textarea name="message" rows="10"></textarea>
<input type="submit"/>
</form>

The HTML page and its inner JavaScript components cannot themselves send the email to the SMTP mail server due to security reasons: they don’t run on the server, but on the client browser and they don’t have access to low-level TCP/IP protocols that are required to authenticate and communicate with the mail server.

This server-side script which does this instead, acts like an email client which connects to a SMTP mail server and relays the message to it in order to be sent.

The mail server is usually on the same machine with the email client script and therefore shares its IP address, allowing the server to recognize and trust the client:

email form

The corresponding code for this approach, in the well-known server-side programming language PHP, uses the mail() function and is very succinct:

PHP code

function SimpleSendEmail($from, $to, $subject, $message)
{
    $headers = "From: $from \r\n
                   Reply-To: $from \r\n
               X-Mailer: PHP/".phpversion();
       
    mail($to, $subject, $message, $headers);
}

You’ll have to upload these scripts to a web server under your control, which can run PHP and has a mail server installed. [form image by r0ash]