intermediate

Create a Contact Form for Your Website Using HTML

Updated November 9th, 2024

A method of contact on your developer portfolio is essential, there are several ways to do this. Most people believe that just including your socials (GitHub, LinkedIn, X...) is sufficient, however only having these forms of contact on your portfolio is introducing a potential barrier between you and users.

Not all visitors of your site will have these socials, and some might prefer to keep their socials private and separate from work. An easy way to ensure users have a way of contacting you is simply including your email.

Making your email public can have its disadvantages, users can use it to attack you by social engineering and email phishing. By making a contact form, you can keep your email private, while still keeping an open method of communication.

HTML Elements Needed For Form

Before diving into making our contact form functional, it's important to understand the HTML elements needed for the form and why they are necessary

  1. <form> Tag

    • Importance: The <form> tag is the container for all contact form elements. It defines the boundaries of the form, making sure that all inputs and buttons are grouped together to be processed when a user submits their message.
    • Notes:
      • action: Specifies where form data will be sent, typically this will be a server endpoint that processes the information.
      • method='POST': Including "Post" method for your HTML contact form improves security by sending data without exposing it in the URL, making it less visible.
      • onsubmit: Calls a function when a form is submitted
  2. <label> Tag

    • Importance: The <label> tag is used to enhance accessibilty and usabilty for your forms by clearly defining a clear description for <input/> fields. They also help screen readers, making the form accessible for users with disabilities.
    • Importance for SEO: Using a <label> tag lets you subtly reinforce relevant keywords that describe your form fields.
  3. <input/> Tag

    • Importance: The <input/> tag is used to allow the user to enter information. For a developer portfolio with a contact form, this is typically set to have user's name and email.
    • Input Types:
      • Text Input allows all text to be entered, used for user's name.
      • Email Input ensures users enter valid email address, and on mobile opens email-specific keyboards.
    • Notes:
      • required: checks if user has field filled out with expected information, disallows submit event for contact form from succeeding.
      • placeholder: allows you enter a hint inside the input field, to give users an idea of how the information should be formatted.
  4. <textarea/> Tag

    • Importance: The <textarea/> tag is typically used for larger text entries. Best used for form fields that require a lot of information, like the body of an email.
    • Placeholder: a hint like "Type Your Message" is best to clarify the fields purpose.
  5. Submit Button <button type=submit>

    • Importance: The submit button is used to trigger a defined endpoint defined by action.
    • For Usability: use a clear message in the button text like "Submit" or "Send Message"

Build Your Contact Form

Now that you understand the proper HTML elements for your website's html contact form, and how they assist with accessibility for users with disabilities, you can move on to actually building your HTML contact form.

An example of a HTML contact form using these elements

This is the standard structure of an HTML form, while you can change things like the placeholder, values and whether the inputs are required, it is advised to keep these elements in this order.

<!-- Requires onsubmit attribute, first need to define one -->
<form method='POST'>
    <!-- Name Input -->
    <label for='name'>Name:</label>
    <input type='text' id='name' required placeholder='Your name'/>

    <!-- Email Input -->
    <label for='email'>Email:</label>
    <input type='email' id='email' required placeholder='email@domain.com'/>

    <!-- Message Textarea -->
    <label for='message'>Message:</label>
    <textarea required id='message' placeholder='What message would you like to send'/>

    <!-- Message Textarea -->
    <button type='submit'>Submit</button>
</form>

Making Your HTML Contact Form Functional

At this point, you have built a contact form that can collect data from the user (name, email...), however this data isn't useful because there is no function made that can handle sending the data to your email yet.

There are many different ways to implement functionality for your email form, here are a few:

  • EmailJS
    • Best for: Users who want to avoid setting up a server and prefer a Javascript-only solution
    • Description: EmailJS lets you sends emails directly from JavaScript by integrating with popular email services like Gmail, Outlook and others. You just need to set up an email template (how they emails are structed when sent to you), and a simple script in your website for your form.
    • Free tier available
  • Formspree
    • Best for: Beginners looking for simplest way to add email functionality with minimal configuration
    • Description: Lets you provide server-side email processing service. Just add your unique form endpoint as the form's action attribute, and Formspree takes care of sending the email
    • Free tier available
  • Getform
    • Best for: Users looking for a Formspree alternative with a bit more customization.
    • Description: Getform provides server-side handling for HTML forms, letting you receive form submissions in your email. Getform also supports file uploads, spam protection, and integrations with other services.
    • Free tier available with paid plan for advanced features
  • Netlify Forms
    • Best for: Developers already using Netlify to host their website.
    • Description: Lets you handle form submissions without a back-end server. Integrates seamlessly with Netlify-hosted sites, offering spam protection and form notifications
    • Free tier available
  • Custom Server or Serverless Function
    • Best for: Advanced users who want full control and already have a back-end server or are familiar with cloud functions.
    • Description: Create custom API endpoint using a back-end server like Node.js, or serverless function like AWS Lambda. This function you create will handle the form data and send the email using an email API like SendGrid, Mailgun, or Nodemailer
    • Requires server/cloud function, may incur costs with email APIs

Use EmailJS to implement functionality of HTML Contact Form

To get started, you are going to want to make sure that you have an account with EmailJS, once completed follow these steps

  1. Create a new Email Service

    • Navigate to the Email Services tab on your admin dashboard. Select Add New Service and choose the Personal Services options that fits your email provider (Gmail, AOL, Outlook...).
    • Follow the instructions to Config Service and then click Create Service button.
  2. Create an email template

    • Navigate to Email Templates page in your admin dashboard, and click Create New Template.
    • Write a template to structure emails sent to you.
    • Fill in the additional email fields: To Email, From Name, From Email, Reply To, Bcc and Cc.
    • Optional Create an auto reply template, useful if you do not check your emails often and want the user to know to expect a delay in response.
  3. Write a JavaScript script in your website to use EmailJS to send your email on form submit

In the head of your website add the following script to load EmailJS SDK

<script
  type="text/javascript"
  src="https://cdn.jsdelivr.net/npm/@emailjs/browser@4/dist/email.min.js">
</script>

Initialize the SDK

emailjs.init({
  publicKey: 'YOUR_PUBLIC_KEY', <!-- Public Key from EmailJS found in your account page -->
});

Create a function to use EmailJS to send email after contact form submit

function sendEmail(e) {
    e.preventDefault(); // Prevent the default form submission
    
    emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', e.target)
    .then(function(response) {
        alert('Message sent successfully!');
    }, function(error) {
        alert('Failed to send the message. Please try again later.');
    });
}

The head of your website should look like this now

<head>
    <title>Website title</title>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/@emailjs/browser@4/dist/email.min.js"></script>
    <script type="text/javascript">
        (function() {
            // https://dashboard.emailjs.com/admin/account
            emailjs.init({
              publicKey: "YOUR_PUBLIC_KEY",
            });
        })();
    </script>
    <script type="text/javascript">
        function sendEmail(e) {
            e.preventDefault(); // Prevent the default form submission
    
            <!-- Find Service ID from Email Service created in Step 1 -->
            <!-- Find Template ID from Email Template created in Step 2 -->

            emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', e.target)
              .then(function(response) {
                alert('Message sent successfully!');
              }, function(error) {
                alert('Failed to send the message. Please try again later.');
              });
          }    
     </script>
</head>

Last step, add an Event Listener to your form by adding onsubmit='send

Your HTML contact form should now look like

<form onsubmit='sendEmail(event)' method='POST'>
    <!-- Name Input -->
    <label for='name'>Name:</label>
    <input type='text' id='name' name='name' required placeholder='Your name'/>

    <!-- Email Input -->
    <label for='email'>Email:</label>
    <input type='email' id='email' name='email' required placeholder='email@domain.com'/>

    <!-- Message Textarea -->
    <label for='message'>Message:</label>
    <textarea required id='message' name='message' placeholder='What message would you like to send'/>

    <!-- Message Textarea -->
    <button type='submit'>Submit</button>
</form>

Style Your Contact Form

Now that the functionality of sending a user an email is complete, you can focus on styling your form.

Resources to help find examples of how to style your contact form

  • Dribbble - Search for "Contact Forms" and choose one that fits your style
  • webportfolios.dev - Browse developer portfolios submitted by our community and check how out they styled their contact form
  • Behance - Similar to dribbble, search for "Contact Forms" and choose one that fits your style

It's important to make the contact form design you find your own. Ideally it should match the design you already have for the rest of your website.

Conclusion

Don't wait any longer-go ahead and add a contact form to your portfolio. It's a simple but effective way to make your website more professional.

Other intermediate Guides