How to Build a Contact Form Using the Telegram API

Building an HTML contact form that sends messages to Telegram.
How to Build a Contact Form Using the Telegram API

If you are a blogger or just starting out with web development, adding a contact form usually means dealing with PHP backends, servers, or paying for premium contact form plugins.

But you can actually bypass all of that. By using the Telegram API, you can build a lightweight contact form using just HTML, CSS, and JavaScript. Every time someone submits a message, it will land directly in your Telegram inbox as an instant push notification. Completely free and serverless.


Step 1: The Telegram Setup (Bot & Chat ID)

Before writing any code, you need two things from Telegram: a Bot Token and your Chat ID.

  1. Get a Bot Token: Search for @BotFather on Telegram. Send /newbot, name your bot, and grab the HTTP API Token it gives you.
  2. Get Your Chat ID: Search for @userinfobot on Telegram and press start. It will give you a numeric Id. Copy it.
  3. Important: Open your new bot's chat interface and press Start. If you don't do this, the bot won't be allowed to send you messages.

Step 2: Breaking Down the Code

Let’s understand how each layer of this project works so you can easily tweak it for your blog.

1. The Structure (HTML)

The HTML provides the basic architecture of the form. We need three simple input fields: Name, Email, and Message, followed by a Submit button.

  • We use standard semantic tags like <form>, <input>, and <textarea>.
  • The required attribute ensures users cannot send empty submissions.
  • Every field has a unique id (like id="name") so our JavaScript can grab the data later.

2. The Presentation (CSS)

Clean aesthetics keep users engaged. The CSS handles the alignment, spacing, and modern looks of the form.

  • It wraps the form in a clean card container with a slight drop-shadow.
  • It makes the inputs fully responsive (width: 100%) so it looks great on both mobile phones and desktops.
  • Added a nice focus effect (border-color: #0088cc) to give users visual feedback when they click inside an input field.

3. The Logic (JavaScript)

This is where the magic happens. The JavaScript intercepts the form submission, packages the text, and sends it to Telegram via a background API request.

  • e.preventDefault() prevents the page from reloading when the user clicks submit.
  • document.getElementById().value fetches what the user typed.
  • fetch() handles the actual network request, using a POST method to send a JSON payload containing your chat_id and the message text directly to Telegram’s sendMessage endpoint.
  • Once successful, form.reset() clears the input fields automatically.

Step 3: The Complete Source Code

Here is the combined, fully ready-to-use template. If you are using Blogger, just create a new page, switch the editor to HTML View, and paste this entire block.

Make sure to replace YOUR_BOT_TOKEN and YOUR_CHAT_ID inside the script block with your actual credentials.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact Us</title>
    <style>
        .tg-contact-wrapper {
            max-width: 450px;
            margin: 40px auto;
            padding: 25px;
            background: #ffffff;
            border: 1px solid #e2e8f0;
            border-radius: 10px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
        }
        .tg-contact-wrapper h2 {
            margin-top: 0;
            margin-bottom: 20px;
            color: #1a202c;
            text-align: center;
        }
        .form-group {
            margin-bottom: 18px;
        }
        .form-group label {
            display: block;
            margin-bottom: 6px;
            font-weight: 600;
            color: #4a5568;
            font-size: 0.9rem;
        }
        .form-group input, .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #cbd5e0;
            border-radius: 6px;
            box-sizing: border-box;
            font-size: 1rem;
            transition: all 0.2s ease;
        }
        .form-group input:focus, .form-group textarea:focus {
            outline: none;
            border-color: #0088cc;
            box-shadow: 0 0 0 3px rgba(0, 136, 204, 0.15);
        }
        .btn-submit {
            width: 100%;
            background-color: #0088cc;
            color: white;
            border: none;
            padding: 12px;
            font-size: 1rem;
            font-weight: bold;
            border-radius: 6px;
            cursor: pointer;
            transition: background 0.2s ease;
        }
        .btn-submit:hover {
            background-color: #0077b5;
        }
    </style>
</head>
<body>

<div class="tg-contact-wrapper">
    <h2>Get In Touch</h2>
    <form id="telegram-contact-form">
        <div class="form-group">
            <label for="name">Full Name</label>
            <input type="text" id="name" required placeholder="Your name">
        </div>
        <div class="form-group">
            <label for="email">Email Address</label>
            <input type="email" id="email" required placeholder="yourname@example.com">
        </div>
        <div class="form-group">
            <label for="message">Message</label>
            <textarea id="message" rows="5" required placeholder="Type your message here..."></textarea>
        </div>
        <button type="submit" class="btn-submit">Send Message</button>
    </form>
</div>

<script>
document.getElementById('telegram-contact-form').addEventListener('submit', function(e) {
    e.preventDefault();

    const BOT_TOKEN = 'YOUR_BOT_TOKEN'; 
    const CHAT_ID = 'YOUR_CHAT_ID';

    const name = document.getElementById('name').value;
    const email = document.getElementById('email').value;
    const message = document.getElementById('message').value;

    const formattedText = `📩 *New Contact Submission*\n\n👤 *Name:* ${name}\n📧 *Email:* ${email}\n💬 *Message:* ${message}`;

    const telegramUrl = `https://api.telegram.org/bot\${BOT_TOKEN}/sendMessage`;

    fetch(telegramUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            chat_id: CHAT_ID,
            text: formattedText,
            parse_mode: 'Markdown'
        })
    })
    .then(response => {
        if (response.ok) {
            alert('Message sent successfully!');
            document.getElementById('telegram-contact-form').reset();
        } else {
            alert('Error sending message. Check configuration.');
        }
    })
    .catch(error => {
        console.error('Network Error:', error);
        alert('Network error. Please try again.');
    });
});
</script>

</body>
</html>

Wrapping Up

A quick security heads-up: Since this runs purely on the client side (JavaScript in the browser), anyone who views your site's source code can see your Bot Token. For standard blogs or personal portfolios, this is completely fine. However, if you scale up or handle high-security traffic, it is always a good practice to route this request through a hidden backend environment later on.

Give it a run, test it out, and watch those instant notifications drop into your chat!

Post a Comment