How to send emails from your web server with  PHPMailer

How to send emails from your web server with  PHPMailer

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:

  • Install the library with Composer or manually
  • Configure SMTP settings for reliable delivery
  • Use core PHPMailer components like setFrom(), addAddress(), and Body
  • Create a working contact form with validation
  • Connect PHPMailer to Gmail and other providers
  • Troubleshoot common errors like SMTP connection failures and DNS authentication issues

What is PHPMailer?

PHPMailer is a PHP library that provides a simple way to send emails directly from a server. Unlike the basic PHP mail() function, it supports advanced features like:

  • SMTP authentication and encryption (SSL/TLS)
  • HTML messages and plain text alternatives
  • File attachments and inline images
  • Custom headers and reply-to addresses

These capabilities make PHPMailer the preferred choice for developers who need secure and professional email handling in their applications.

Is PHPMailer better than the mail() function?

Yes, PHPMailer is better than the mail() function for most use cases. Here’s why:

  • Reliability. Works with SMTP, reducing the chance of emails landing in spam.
  • Security. Supports modern authentication methods like TLS.
  • Flexibility. Allows attachments, HTML formatting, and advanced headers.
  • Compatibility. Widely supported and updated with new PHP versions.

If you’re building anything beyond the simplest script, PHPMailer offers far more control and consistency than mail().

How to use PHPMailer to send emails

Follow these general steps to send emails with PHPMailer:

  1. Download and install PHPMailer using Composer or GitHub.
  2. Load the library in your PHP script with an autoloader or manually.
  3. Create a new PHPMailer instance.
  4. Configure SMTP settings (server, port, username, password).
  5. Set email details like sender, recipient, subject, and body.
  6. Send the email and handle potential errors.

Here’s a simple example:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

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}";
}

Installing PHPMailer

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.

Understanding PHPMailer components

PHPMailer provides many methods and properties to build professional emails. Here are the most important ones, along with short examples you can reuse:

  • setFrom() – defines the sender’s address and name.
 $mail->setFrom('no-reply@domain.com', 'Website Name');
  • addAddress() – adds one or more recipients.
 $mail->addAddress('user@example.com', 'John Doe');
$mail->addAddress('admin@example.com'); // multiple recipients
  • addReplyTo() – specifies the reply-to email. Useful for contact forms.
 $mail->addReplyTo('support@domain.com', 'Support Team');
  • Subject – sets the subject line of the email.
 $mail->Subject = 'Order Confirmation';
  • Body – the main HTML or plain text content.
 $mail->Body = '<h1>Thank you!</h1><p>Your order has been received.</p>';
  • AltBody – plain-text fallback for clients that don’t support HTML.
 $mail->AltBody = 'Thank you! Your order has been received.';
  • addAttachment() – attaches files.
 $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.

Using PHPMailer with Hostinger SMTP

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:

  • SMTP server: smtp.hostinger.com
  • Port: 587 (TLS) or 465 (SSL)
  • Username: your full email address (for example, yourname@yourdomain.com)
  • Password: the password for that email account

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:

  • Make sure you’ve already created an email account in hPanel → Emails → Manage → Create new account.
  • The SMTP password is the one you set when creating the email account, not your Hostinger login password.
  • Test your credentials in Webmail first. If you can log in there, they should also work with PHPMailer.

Once configured, PHPMailer will use Hostinger’s servers to deliver emails securely.

Creating a PHPMailer contact form

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 PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

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:

  • Validate input on both client and server sides to prevent spam and abuse.
  • Set From to an address on your domain. Use addReplyTo() for the visitor’s email so replies go to them.
  • Consider adding a simple honeypot field or CAPTCHA to reduce bot submissions.

How to troubleshoot PHPMailer errors

PHPMailer provides detailed error messages. Here are some common ones:

Could not connect to SMTP host

This error usually means your SMTP server address or port is incorrect. Common causes include:

  • Wrong server name. Double-check your hosting provider’s SMTP details. For example, with Hostinger, it’s usually smtp.hostinger.com.
  • Blocked port. Many servers block port 25. Instead, use port 587 (TLS) or 465 (SSL).
  • Firewall restrictions. If you’re testing locally (like on XAMPP or WAMP), your ISP or firewall may block outgoing SMTP connections.

👉 If you’re unsure, ask your hosting provider which SMTP settings to use and confirm whether ports are open on your network.

SMTP connect() failed

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:

  • Username issues. Always use your full email address as the SMTP username.
  • Incorrect password. If you changed your email password recently, update it in your script.
  • Encryption mismatch. Make sure you’re using the correct security method. For example:
    • Port 587 → PHPMailer::ENCRYPTION_STARTTLS
    • Port 465 → PHPMailer::ENCRYPTION_SMTPS

👉 If the problem persists, try logging into your email account via webmail to confirm the credentials are correct.

Message rejected due to SPF/DKIM/DMARC

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:

  • SPF (Sender Policy Framework). Tells mail servers which IPs or hosts can send emails for your domain.
  • DKIM (DomainKeys Identified Mail). Adds a digital signature that verifies your message wasn’t tampered with.
  • DMARC (Domain-based Message Authentication, Reporting & Conformance). Tells receiving servers how to handle messages that fail SPF or DKIM checks.

👉 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.

Can I send emails from PHPMailer to Gmail or other email services?

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:

  • SMTP server: smtp.gmail.com
  • Port: 587 (TLS) or 465 (SSL)
  • Username: your full Gmail address
  • Password: your App Password if 2-step verification is enabled
  • In your Google Account, create an App Password under Security → 2-Step Verification → App passwords and use it in $mail->Password.

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:

  • Use the provider’s recommended port and encryption.
  • Authenticate with the correct credentials.
  • Set From to a domain you control for better deliverability.
  • Add SPF, DKIM, and DMARC records to your domain to build trust.

Is email still the backbone of online services?

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.

All of the tutorial content on this website is subject to Hostinger's rigorous editorial standards and values.

Author
The author

Matleena Salminen

Matleena is a seasoned Content Writer with 5 years of content marketing experience. She has a particular interest in emerging digital marketing trends, website building, and AI. In her free time, Matleena enjoys cups of good coffee, tends to her balcony garden, and studies Japanese. Follow her on LinkedIn