To send a contact form to email, post the form to a small server-side handler. The handler validates the fields, filters spam, and calls an email API with your own address in From and the visitor’s address in Reply-To. The API key stays on the server. When you press reply in your inbox, the answer goes straight to the visitor.
The shape of a safe contact form
Browser form -> your server handler -> email API -> your inbox
(validate, honeypot,
rate limit, escape)
Each part has a job:
- The form collects name, email and message, plus a hidden honeypot field.
- The handler rejects bots, checks lengths and formats, and builds the email.
- The email API delivers from your verified domain.
Best practices
- Your address in From, theirs in Reply-To. Putting the visitor in From fails DMARC because you do not own their domain.
- Never ship the API key to the browser. Anything in client-side JavaScript is readable by anyone.
- Honeypot. A field hidden with CSS that people leave empty and bots fill in. If it has a value, pretend success and send nothing.
- Rate limit per IP, such as a few submissions per minute.
- Validate on the server. Required fields, an email that looks like one, a maximum message length.
- Escape before HTML. A visitor can type
<script>or a phishing link. Escape the text and put it in a plain layout. - Avoid confirmation emails to the typed address. Spammers abuse them to send to strangers through your domain.
- Use a verified domain. Without SPF, DKIM and DMARC the submissions land in your own spam folder. See why emails go to spam.
Example submission email
From: Website <website@acme.com>
To: hello@acme.com
Reply-To: Sam Buyer <sam@example.com>
Subject: Contact form: Pricing for 20 seats
Name: Sam Buyer
Email: sam@example.com
Message:
Do you offer annual pricing for a team of 20?
Page: https://acme.com/contact
Next.js contact form with an email API
This is a Next.js App Router route handler. It uses the Mailcandor email API with fetch, so no extra packages are needed.
// app/api/contact/route.ts
const esc = (s: string) =>
s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!);
export async function POST(req: Request) {
const form = await req.formData();
const name = String(form.get('name') ?? '').trim().slice(0, 100);
const email = String(form.get('email') ?? '').trim().slice(0, 200);
const message = String(form.get('message') ?? '').trim().slice(0, 5000);
if (form.get('company_website')) return Response.json({ ok: true }); // honeypot
if (!name || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || !message) {
return Response.json({ error: 'Please fill in every field.' }, { status: 422 });
}
const res = await fetch('https://api.mailcandor.com/v1/emails', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.MAILCANDOR_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
from: 'Website <website@acme.com>',
to: 'hello@acme.com',
reply_to: `${name.replace(/[<>"]/g, '')} <${email}>`,
subject: `Contact form: ${message.slice(0, 60).replace(/\s+/g, ' ')}`,
html: `<p><b>Name:</b> ${esc(name)}<br><b>Email:</b> ${esc(email)}</p><p>${esc(message).replace(/\n/g, '<br>')}</p>`,
text: `Name: ${name}\nEmail: ${email}\n\n${message}`,
tags: [{ name: 'source', value: 'contact_form' }],
}),
});
if (!res.ok) return Response.json({ error: 'Could not send. Please email hello@acme.com.' }, { status: 502 });
return Response.json({ ok: true });
}
Add a rate limit in front of it with your platform’s middleware or edge config. The honeypot input is <input name="company_website" tabindex="-1" autocomplete="off"> inside a container hidden with CSS.
PHP script to send email from an HTML form
For a plain PHP site, the same logic uses PHP’s built-in curl instead of mail():
<?php
// contact.php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit; }
if (!empty($_POST['company_website'])) { header('Location: /thanks'); exit; } // honeypot
$name = trim(substr($_POST['name'] ?? '', 0, 100));
$email = filter_var(trim($_POST['email'] ?? ''), FILTER_VALIDATE_EMAIL);
$message = trim(substr($_POST['message'] ?? '', 0, 5000));
if (!$name || !$email || !$message) { http_response_code(422); exit('Please fill in every field.'); }
$h = fn ($s) => htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
$ch = curl_init('https://api.mailcandor.com/v1/emails');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('MAILCANDOR_KEY'), 'Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode([
'from' => 'Website <website@acme.com>',
'to' => 'hello@acme.com',
'reply_to' => $email,
'subject' => 'Contact form: ' . $name,
'html' => '<p><b>Name:</b> ' . $h($name) . '</p><p>' . nl2br($h($message)) . '</p>',
'text' => "Name: $name\nEmail: $email\n\n$message",
]),
]);
curl_exec($ch);
$ok = curl_getinfo($ch, CURLINFO_HTTP_CODE) === 202;
curl_close($ch);
header('Location: ' . ($ok ? '/thanks' : '/contact?error=1'));
If your site builder or CMS only supports SMTP, use the SMTP relay with the same verified domain. For framework-specific setups, see integrations.
Why use Mailcandor for forms
The free Starter plan covers 3,000 emails a month and 100 a day, which is plenty for most contact forms. Give the form its own sending-only key locked to your domain, so a leaked server config cannot be used to send anything else. Every submission shows in the log with its delivery status, which answers “did that enquiry arrive?” in seconds.
Common pitfalls
- Visitor address in From. DMARC failure, and your form becomes a spoofing tool.
- API key in client code. Anyone can read it and send as you.
- No honeypot or rate limit. Bots find forms within days.
- Unescaped HTML. Visitors can inject links and markup into your inbox.
- Silent failures. If the send fails, tell the visitor and give them an address to write to.
- Using PHP
mail()on shared hosting. The hosting server rarely signs with DKIM for your domain, so submissions vanish into spam with no log to check. - Sending to a single person’s inbox. Use a shared address such as
hello@so enquiries are not lost when someone is away or leaves.