Learn how to send emails securely from your PHP website using PHPMailer and SMTP authentication. Step-by-step guide for beginners with contact form setup and tips: –
Emails are important part of every website—from contact forms or sending notifications. PHP has a built-in mail function, but it often doesn’t work well or goes to spam. That’s why we use PHPMailer with SMTP, which helps send emails reliably, safely, and professionally.
In this guide, we’ll show you from start to finish how to set up PHPMailer, create a contact form, and send emails using SMTP.

- For example, common issues with
mail()include: - Often, Emails often go to spam.
- Lacks proper authentication.
- cannot easily send HTML emails or attachments.
By contrast, PHPMailer offers these advantages:
- it provides detailed error reporting.
- In addition, it supports SMTP authentication.
- it sends HTML emails and attachments easily.
Step 1: Download and Install PHPMailer
Specifically, you have two options:
Option 1: Using Composer (Recommended)
- First, open your project folder in the terminal.
- Then, type
composer require phpmailer/phpmailerand hit Enter. - This will create a vendor folder with all the PHPMailer files inside.
Option 2: Manual Download
- Alternatively, Visit PHPMailer GitHub
- Next, Download the ZIP and extract it to your project folder.
- Add PHPMailer in your PHP file:
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
require 'path/to/PHPMailer/src/Exception.php';Step 2: Create a Simple Contact Form
Create a file contact.html:
After installing PHPMailer, the next step is to make a simple contact form for your website. This will help you collect user details easily.
Here’s what you need to do:
Create a New File
First, Open your text editor or code editor (like VS Code, Notepad++, or Sublime Text) and create a new file. Save it with the name contact.html.Consequently, The .html extension means it will be a web page file.
Create Form in these html file
Ideally, include fields for name, email, subject, and message.
Additionally, add client-side validation and reCAPTCHA.
Connect the Form to the PHP Script
link the form to sendmail.php, which will process the submission and send the email.Then, when someone clicks Submit, the form data is posted to that script.
Test the Form Layout
For now, open contact.html in your browser to preview the fields. At this stage, you won’t send emails yet, but you should see the inputs.
You can also use this source code for reference
<div class="form-container">
<h2>Contact Us</h2>
<form action="sendmail.php" method="post" onsubmit="return validateForm()">
<input type="text" name="name" placeholder="Your Name" required>
<input type="email" name="email" placeholder="✉️[email protected]" required>
<input type="text" name="subject" placeholder="Enter subject" required>
<input type="number" name="Contact" placeholder="Phone No" required>
<textarea name="message" placeholder="Write your message here..." required></textarea>
<!-- Google reCAPTCHA -->
<div class="g-recaptcha" data-sitekey="6Leza6wrAAAAAGF4Yu0vJvYN6oUKnr4Gufoo-Jqw"> </div>
<button type="submit">Submit</button>
</form>
</div>
<script>
function validateForm() {
const email = document.querySelector("input[name='email']").value;
const re = /^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/;
if (!re.test(email)) {
alert("❌ Please enter a valid email address!");
return false;
}
if (grecaptcha.getResponse().length === 0) {
alert("❌ Please verify that you are not a robot.");
return false;
}
return true;
}
</script>Step 3: Make Your Form Attractive
For better UX, use CSS for styling.
Also, add placeholder text and required fields.
Furthermore, include success and error messages after submission.
You can also use this source code for reference
.form-container {
max-width: 450px;
margin: auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 8px;
background: #f9f9f9;
}
.form-container h2 {
text-align: center;
margin-bottom: 20px;
}
.form-container input,
.form-container textarea,
.form-container button {
width: 90%;
margin-bottom: 15px;
padding: 10px;
border-radius: 5px;
border: 1px solid #ccc;
font-size: 16px;
}
.form-container button {
background: #0073e6;
color: white;
cursor: pointer;
}
.form-container button:hover {
background: #005bb5;
}Step 4 : Set up PHPMailer with SMTP
Create sendmail.php :
This step ensures your messages are sent securely and have a much higher chance of avoiding spam folders. Now, here’s how the process works:
1️⃣.First, Create the PHP File — Make a .php file where you’ll write your email code.
2️⃣. Second, Load PHPMailer — include PHPMailer files in that PHP file.
3️⃣. Then, set up SMTP Configuration — Add SMTP detailes like host, port username & password
4️⃣. After that, Add Email Recipients — Writte the email addresses of the sender and reciever
5️⃣. Write Email — Add subject and message content in your email
6️⃣. Finally, Send and Handle Errors — Send email and show success and error message
7️⃣. You can also use this source code for reference
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require __DIR__ . '/phpmailer/src/Exception.php';
require __DIR__ . '/phpmailer/src/PHPMailer.php';
require __DIR__ . '/phpmailer/src/SMTP.php';
// Now your email sending code...
// Collect form data
$name = $_POST['name'] ?? '';
$email = $_POST['email'] ?? '';
$subject = $_POST['subject'] ?? '';
$message = $_POST['message'] ?? '';
if (empty($name) || empty($email) || empty($subject) || empty($message)) {
die("All fields are required!");
}
$mail = new PHPMailer(true);
try {
// Server settings
$mail->isSMTP();
$mail->Host = 'mail.singlens.clinic'; // Change if using another SMTP server
$mail->SMTPAuth = true;
$mail->Username = '[email protected]'; // Your email address
$mail->Password = '********'; // Your email/app password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = 465;
// Recipients
$mail->setFrom('[email protected]', 'Admin');
$mail->addAddress('[email protected]', 'Admin'); //Where you want to receive messages
$mail->addAddress('[email protected]', 'Admin');
$mail->addReplyTo($email, $name);
$secretKey = "YOUR SECRET KEY";
// $captcha = $_POST['g-recaptcha-response'];
if (isset($_POST['g-recaptcha-response'])) {
$captcha = $_POST['g-recaptcha-response'];
} else {
$captcha = false;
}
if (!$captcha) {
die('❌ reCAPTCHA verification failed. Please try again.');
}
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
$responseKeys = json_decode($response, true);
if (empty($responseKeys["success"]) || $responseKeys["success"] !== true) {
die('❌ reCAPTCHA verification failed. Please try again.');
}
// Content
$mail->isHTML(true);
$mail->Subject = "New Contact Form Submission: " . $subject;
$mail->Body = "
<h3>Contact Form Submission</h3>
<p><b>Name:</b> {$name}</p>
<p><b>Email:</b> {$email}</p>
<p><b>Subject:</b> {$subject}</p>
<p><b>Message:</b><br>{$message}</p>
";
$mail->AltBody = "Name: {$name}\nEmail: {$email}\nSubject: {$subject}\nMessage: {$message}";
$mail->send();
echo "✅ Message has been sent successfully!";
} catch (Exception $e) {
echo "❌ Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>Step 5: Test Your Contact Form
1.To begin, upload contact.html and sendmail.php to your server.
2.Then, fill out the form and submit it.
3.As a result, you should receive the email in your inbox.

Step 6: Sending Emails to Multiple Recipients
You can also send the same email to many people. Just add more addAddress() lines, or use addCC() and addBCC() if you want to send copies.
$mail->addAddress('[email protected]');
$mail->addAddress('[email protected]');Step 7: Security Tips
- Most important don’t share your SMTP password publicly.
- Instead Use environment variables or
.envfiles for credentials. - Look wise validate form inputs to prevent spam or injections.
Conclusion:
PHPMailer with SMTP authentication ensures that your emails are delivered securely and reliably. Moreover, it helps reduce the chances of your emails being marked as spam.
- Send HTML emails.
- Send attachments.
- Handle errors easily.
- Reach multiple recipients.
Leave a Reply