Written by: Geoffrey Callaghan

How to Create an HTML Form That Sends You an Email

How To Create An Html Form That Sends You An Email

Creating an HTML form that sends you an email using Fabform involves setting up the form in your HTML file and configuring a backend to handle the form submission and send the email. Fabform helps with generating the HTML form fields and handling form submissions on the client-side. Here’s a step-by-step guide:

  1. Set Up Your HTML Form: Create an HTML file in your project where you want to include the contact form.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Contact Form</title>
    </head>
    <body>
        <h1>Contact Us</h1>
        <form id="contactForm">
            <div>
                <label for="name">Name:</label>
                <input type="text" id="name" name="name" required>
            </div>
            <div>
                <label for="email">Email:</label>
                <input type="email" id="email" name="email" required>
            </div>
            <div>
                <label for="message">Message:</label>
                <textarea id="message" name="message" required></textarea>
            </div>
            <button type="submit">Submit</button>
        </form>
    
        <script src="https://cdn.jsdelivr.net/npm/fabform@1.1.0/dist/fabform.min.js"></script>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                var form = document.getElementById('contactForm');
                var fabform = new Fabform(form);
    
                fabform.onSubmit(function(formData) {
                    // Send form data to your backend for processing
                    sendFormData(formData);
                });
    
                function sendFormData(formData) {
                    // Implement your backend logic here to send an email
                    // You can use fetch or XMLHttpRequest to send data to your backend endpoint
                    fetch('/send-email', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(formData)
                    }).then(function(response) {
                        if (response.ok) {
                            console.log('Form submitted successfully');
                            // Optionally, show a success message or redirect the user
                        } else {
                            console.error('Form submission failed');
                            // Optionally, show an error message to the user
                        }
                    }).catch(function(error) {
                        console.error('Error:', error);
                        // Optionally, show an error message to the user
                    });
                }
            });
        </script>
    </body>
    </html>
  2. Set Up Your Backend: Create a backend endpoint to handle the form submission and send the email. You can use a server-side language like Node.js with Express, Ruby on Rails, PHP, etc. Here’s an example using Node.js with Express:

    const express = require('express');
    const bodyParser = require('body-parser');
    const nodemailer = require('nodemailer');
    
    const app = express();
    const port = 3000;
    
    app.use(bodyParser.json());
    
    // POST endpoint to handle form submission
    app.post('/send-email', (req, res) => {
        const { name, email, message } = req.body;
    
        // Create a transporter using SMTP
        const transporter = nodemailer.createTransport({
            service: 'Gmail',
            auth: {
                user: 'your-email@gmail.com',
                pass: 'your-password'
            }
        });
    
        // Define email options
        const mailOptions = {
            from: 'your-email@gmail.com',
            to: 'your-email@gmail.com',
            subject: 'New Contact Form Submission',
            text: `Name: ${name}\nEmail: ${email}\nMessage: ${message}`
        };
    
        // Send email
        transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                console.error('Error sending email:', error);
                res.status(500).send('Error sending email');
            } else {
                console.log('Email sent:', info.response);
                res.status(200).send('Email sent successfully');
            }
        });
    });
    
    app.listen(port, () => {
        console.log(`Server listening at http://localhost:${port}`);
    });

    Make sure to replace 'your-email@gmail.com' and 'your-password' with your email credentials.

  3. Test Your Form: Open your HTML file in a browser, fill out the form, and submit it. You should receive an email with the form data.

This setup allows you to create an HTML form using Fabform and handle the form submission on the client-side while using a backend to send the email. Make sure to implement proper error handling and security measures in your backend code.