Skip to content

How to Send Email from PHP with SMTP (PHPMailer)

2 min read

Applies to: PHPMailer 7 with PHP 8.1 or later (cPanel hosting, VPS and dedicated servers)

PHP’s built-in mail() function sends without logging in, so the mail often lands in spam or isn’t sent at all. Sending through an SMTP account with a login is far more reliable. PHPMailer is the most widely used PHP library for that. We tested the example below with PHPMailer 7.1.1.

1. Install PHPMailer with Composer

cd /path/to/your/site
composer require phpmailer/phpmailer

On cPanel hosting, run it over SSH in your site’s folder.

2. Send a message

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require __DIR__ . '/vendor/autoload.php';

$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host       = 'mail.example.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'website@example.com';
    $mail->Password   = getenv('SMTP_PASSWORD');   // keep it out of the code
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;  // port 465; or ENCRYPTION_STARTTLS with port 587
    $mail->Port       = 465;

    $mail->setFrom('website@example.com', 'Example Website');
    $mail->addAddress('customer@example.net');
    $mail->addReplyTo('info@example.com');
    $mail->Subject = 'Thanks for your message';
    $mail->Body    = 'We received your message and will reply soon.';

    $mail->send();
    echo 'sent';
} catch (Exception $e) {
    echo 'failed: ' . $mail->ErrorInfo;
}

Settings to get right

  • Username and From: use a real mailbox on your domain and send from that address. Put visitors’ addresses in Reply-To, never in From.
  • Port: 465 with SMTPS or 587 with STARTTLS; see SMTP port numbers.
  • SPF and DKIM for the domain, so the mail isn’t marked as spam: cPanel Email Deliverability.
  • Debugging: add $mail->SMTPDebug = 2; temporarily to see the conversation with the server.

WordPress

WordPress already includes PHPMailer. Use an SMTP plugin to send through your mailbox instead of writing code.

Related services

KVM VPS hosting

NVMe SSD and full root access, with Free Basic Managed Support.

Managed cPanel VPS

cPanel included; we handle updates, security and monitoring.

Server management

on-demand administration, hardening, migrations and monitoring.

Was this answer helpful?

Still stuck? Open a ticket