In this article · 7 sections
Many website contact forms "work" but emails never arrive, or land in spam. The usual cause is PHP's basic mail() function. Sending through an authenticated mail server with PHPMailer SMTP fixes most delivery problems.
1. Get PHPMailer
With Composer:
composer require phpmailer/phpmailer
Or download the release from GitHub and include the files from its src folder.
2. SMTP settings
| Provider | Host | Port | Security |
|---|---|---|---|
| Hostinger email | smtp.hostinger.com | 465 | SSL |
| Google Workspace / Gmail | smtp.gmail.com | 587 | STARTTLS (use an App Password with 2FA) |
| Zoho Mail | smtp.zoho.in | 465 | SSL |
Check your provider's current settings.
3. The form handler
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require __DIR__ . '/vendor/autoload.php';
$name = trim($_POST['name'] ?? '');
$email = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);
$msg = trim($_POST['message'] ?? '');
if ($name === '' || !$email || $msg === '' || !empty($_POST['website'])) {
http_response_code(400);
exit('Please fill all fields correctly.');
}
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.hostinger.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = getenv('SMTP_PASS');
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = 465;
$mail->CharSet = 'UTF-8';
$mail->setFrom('[email protected]', 'Website Enquiry');
$mail->addAddress('[email protected]');
$mail->addReplyTo($email, $name);
$mail->Subject = 'New enquiry from ' . $name;
$mail->Body = "Name: $name\nEmail: $email\n\n$msg";
$mail->send();
echo 'Thank you! We will reply soon.';
} catch (Exception $e) {
error_log('Mail error: ' . $mail->ErrorInfo);
echo 'Sorry, something went wrong. Please call us.';
}
Key points:
- From must be your own domain mailbox; put the visitor's address in Reply-To
- Keep the SMTP password out of code where possible (environment variable or a config file outside
public_html) - Don't show
ErrorInfoto visitors; log it
4. Stop spam
- A hidden honeypot field (the
websitefield above) that bots fill and humans don't - Rate limiting per IP
- CAPTCHA (e.g. Cloudflare Turnstile) if spam continues
5. Deliverability
Set SPF, DKIM and DMARC for your domain so mail is trusted. See business email SPF, DKIM, DMARC.
Troubleshooting
| Error | Likely fix |
|---|---|
| SMTP connect() failed | Wrong host/port, or the host blocks outbound SMTP on that port |
| Authentication failed | Wrong password; Gmail needs an App Password |
| Emails in spam | Missing SPF/DKIM, From address not your domain |
See also contact form not working: fixes.
FAQs
Can I also save enquiries to a database?
Yes, and you should, so leads aren't lost if email fails. See MySQL basics.
Should I send an auto-reply to the customer?
It's helpful. Use a second email to the visitor with your contact details.
Was this article helpful?
Your answer helps us improve our guides