Dec 02, 2025
Matleena S.
6min Read
Dec 02, 2025
Matleena S.
6min Read
Email is essential for websites. It handles everything from password resets to customer inquiries. The PHP mail() function can send simple messages, but it often fails to deliver to inboxes and lacks features businesses rely on.
PHPMailer fixes these problems by providing authenticated SMTP, secure encryption, HTML formatting, and support for attachments. This ensures your messages look professional and actually reach recipients.
To get the most out of PHPMailer, you should know how to:
PHPMailer is a PHP library that provides a simple way to send emails directly from your web server. Unlike the basic PHP mail() function, it supports advanced features like:
These capabilities make PHPMailer the preferred choice for developers who need secure and professional email handling in their applications.
Yes, PHPMailer is better than the mail() function for most use cases. Here’s why:
If you’re building anything beyond the simplest script, PHPMailer offers far more control and consistency than mail().
Follow these general steps to send emails with PHPMailer:
Here’s a simple example:
<?php
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// SMTP configuration
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@email.com';
$mail->Password = 'password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
// Email settings
$mail->setFrom('your@email.com', 'Your Name');
$mail->addAddress('recipient@domain.com');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email sent using PHPMailer.';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Error: {$mail->ErrorInfo}";
}
The easiest way to install PHPMailer is with Composer, the PHP dependency manager. Run this command in your project’s root directory:
composer require phpmailer/phpmailer
After installation, you’ll see PHPMailer inside the vendor/ folder of your project:
/your-project
/vendor
/phpmailer
/phpmailer
To use it, load the Composer autoloader at the top of your PHP script:
require 'vendor/autoload.php';
If you don’t use Composer, you can also download PHPMailer from GitHub. In that case, place the PHPMailer folder in your project and include the files manually:
require 'PHPMailer/src/PHPMailer.php'; require 'PHPMailer/src/SMTP.php'; require 'PHPMailer/src/Exception.php';
Composer is strongly recommended for beginners since it handles dependencies and makes updates easier.
PHPMailer provides many methods and properties to build professional emails. Here are the most important ones, along with short examples you can reuse:
$mail->setFrom('no-reply@domain.com', 'Website Name'); $mail->addAddress('user@example.com', 'John Doe');
$mail->addAddress('admin@example.com'); // multiple recipients
$mail->addReplyTo('support@domain.com', 'Support Team');$mail->Subject = 'Order Confirmation';
$mail->Body = '<h1>Thank you!</h1><p>Your order has been received.</p>';
$mail->AltBody = 'Thank you! Your order has been received.';
$mail->addAttachment('/path/to/invoice.pdf', 'Invoice.pdf');
These building blocks give you full control over how your email looks and works, making it more reliable than PHP’s basic mail() function.
Most hosting providers, including Hostinger, allow you to send emails using their SMTP servers. This is the recommended method, as it improves deliverability and reduces the risk of your emails being flagged as spam.
To use Hostinger’s SMTP with PHPMailer, you’ll need these details:
Here’s an example configuration:
$mail->isSMTP(); $mail->Host = 'smtp.hostinger.com'; $mail->SMTPAuth = true; $mail->Username = 'your@hostinger.com'; $mail->Password = 'password'; $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // or ENCRYPTION_SMTPS for port 465 $mail->Port = 587;
🔑 Beginner tips:
Once configured, PHPMailer will use Hostinger’s servers to deliver emails securely.
PHPMailer is often used for contact forms. You’ll need an HTML form on the page and a PHP handler that uses PHPMailer to send the message.
Step 1. Add a basic HTML form
This form will collect the visitor’s name, email, and message. Save it as index.html or place it inside your webpage:
<form method="POST" action="/contact.php"> <label for="name">Name</label> <input id="name" name="name" type="text" required> <label for="email">Email</label> <input id="email" name="email" type="email" required> <label for="message">Message</label> <textarea id="message" name="message" rows="6" required></textarea> <button type="submit">Send</button> </form>
Step 2. Handle the POST request with PHPMailer
Now that the form is ready, create a PHP script (contact.php) to process the submission and send it via PHPMailer. This script takes the submitted form data, sanitizes it, and sends it to your email address:
<?php
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
require 'vendor/autoload.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Basic validation and sanitization
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$message = trim($_POST['message'] ?? '');
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
exit('Invalid email address.');
}
// Escape user content before including it in HTML
$safeName = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
$safeEmail = htmlspecialchars($email, ENT_QUOTES, 'UTF-8');
$safeMessage = nl2br(htmlspecialchars($message, ENT_QUOTES, 'UTF-8'));
$mail = new PHPMailer(true);
try {
// SMTP
$mail->isSMTP();
$mail->Host = 'smtp.hostinger.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@hostinger.com';
$mail->Password = 'password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // 587
$mail->Port = 587;
// Email content
$mail->setFrom('your@hostinger.com', 'Website Contact');
$mail->addAddress('your@hostinger.com', 'Inbox');
$mail->addReplyTo($email, $name);
$mail->Subject = 'New contact form submission';
$mail->isHTML(true);
$mail->Body = "<p><strong>Name:</strong> {$safeName}</p>
<p><strong>Email:</strong> {$safeEmail}</p>
<p><strong>Message:</strong><br>{$safeMessage}</p>";
$mail->AltBody = "Name: {$name}nEmail: {$email}nMessage:n{$message}";
// Optional file upload
// if (!empty($_FILES['attachment']['tmp_name'])) {
// $mail->addAttachment($_FILES['attachment']['tmp_name'], $_FILES['attachment']['name']);
// }
$mail->send();
echo 'Message sent successfully.';
} catch (Exception $e) {
echo 'Error: ' . $mail->ErrorInfo;
}
}
Useful tips:
PHPMailer provides detailed error messages. Here are some common ones:
This error usually means your SMTP server address or port is incorrect. Common causes include:
👉 If you’re unsure, ask your hosting provider which SMTP settings to use and confirm whether ports are open on your network.
This error often points to failed authentication. In other words, PHPMailer is reaching the server, but your login details aren’t accepted. This could be because of:
👉 If the problem persists, try logging into your email account via webmail to confirm the credentials are correct.
This means the recipient’s mail server rejected your message because your domain doesn’t have proper authentication records. These are DNS records that prove you’re authorized to send email from your domain:
👉 To fix this, log in to your domain registrar or hosting panel and add the required DNS records. Most hosting providers, including Hostinger, provide step-by-step guides for setting up SPF, DKIM, and DMARC.
Without these records, your emails are much more likely to land in spam or be rejected entirely.
Yes. PHPMailer works with Gmail, Outlook, Yahoo, and most other providers. You just need the correct SMTP settings and authentication method. For example, use these specs for Gmail:
Example:
$mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = 'yourname@gmail.com'; $mail->Password = 'your-app-password'; // not your regular login $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587;
There may be some provider limits to consider. Many free mailboxes limit daily sends. For example, Gmail has a low daily cap for SMTP. If you need higher volume or faster delivery, consider a dedicated email service in the future. PHPMailer can talk to any SMTP server, so switching later is straightforward.
General checklist:
Absolutely. Email remains the most reliable way to deliver transactional messages, marketing campaigns, and customer support replies, even as new communication tools emerge. For businesses, professional email setups with automation save time and improve engagement.
If you want to scale beyond manual emails, explore email marketing automation to streamline campaigns and customer communication.