PHPMailer: Send Email With SMTP in PHP

A PHP contact form needs a way to send its messages to an email provider. PHPMailer is a PHP library that builds email messages and submits them over SMTP, a protocol for sending messages from an application to a server.

I’ll show how to install PHPMailer with Composer, then configure it to send a message through SMTP.

TL;DR

Install PHPMailer with Composer, connect it to your provider’s SMTP server, and keep the password outside the PHP source.

  • Install the package with composer require phpmailer/phpmailer.
  • Load Composer’s vendor/autoload.php file in the sending script.
  • Set SMTP host, port, encryption and credentials from your provider’s current settings.
  • Use send() as a transport result, then check logs and delivery separately.

What Is PHPMailer?

PHPMailer is a PHP library for composing email and submitting it through local mail transport or SMTP. It handles address validation, MIME formatting, attachments and HTML with a plain-text alternative.

SMTP is the protocol an application uses to submit a message to a mail server. PHPMailer acts as the client, while the provider authenticates the account and accepts or rejects the submission.

The PHP mail() function depends on a configured local transport and reports whether that transport accepted a message. PHPMailer helps when an app needs SMTP authentication, TLS settings, structured fields or diagnostic output.

Use the official PHPMailer repository for installation and examples. Composer is the route here because it installs the package and maintains the project’s class autoloader.

How to Send Email With PHPMailer and SMTP

The sending path has four parts: add the dependency, load its classes, configure an authenticated SMTP connection, then create and send a message. You need PHP, Composer, an SMTP account, and that provider’s hostname, port, encryption mode and credential method.

Step 1: Install PHPMailer With Composer

Run Composer from the directory that contains the PHP project. The package adds the dependency and creates vendor/autoload.php. Avoid copying standalone class files into a new project.

composer require phpmailer/phpmailer

Commit the generated composer.json and composer.lock when the project uses version control, but do not commit credentials. On a server deployment, install dependencies with the project’s normal Composer deployment process.

Step 2: Load Classes and Configure SMTP

Load the autoloader before creating a PHPMailer instance. The example reads credentials from environment variables so a password is not stored in a tracked source file.

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;

require __DIR__ . '/vendor/autoload.php';

$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = getenv('SMTP_HOST');
$mail->SMTPAuth = true;
$mail->Username = getenv('SMTP_USER');
$mail->Password = getenv('SMTP_PASS');
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
$mail->CharSet = 'UTF-8';

Port 587 is commonly used with STARTTLS. Other services specify implicit TLS on port 465, so set the port and encryption constant to the values documented by the provider.

Step 3: Set the Sender and Recipient

Use a sender address the authenticated account is allowed to use. The provider may reject a different From identity as spoofing. For contact forms, validate the visitor’s address and add it as Reply-To.

$mail->setFrom('[email protected]', 'Site notifications');
$mail->addAddress('[email protected]', 'Reader');
$mail->addReplyTo('[email protected]', 'Support team');
$mail->Subject = 'Your request was received';

Step 4: Add Plain Text and HTML, Then Send

Set isHTML(true) for formatted email and provide AltBody as the text alternative. Mail clients that cannot display HTML can use that alternative instead.

$mail->isHTML(true);
$mail->Body = '<p>Your request is being processed.</p>';
$mail->AltBody = 'Your request is being processed.';

try {
    $mail->send();
    // The SMTP server accepted the message for processing.
} catch (\PHPMailer\PHPMailer\Exception $e) {
    error_log('Mail send failed: ' . $mail->ErrorInfo);
}

When PHPMailer returns successfully from send(), the configured SMTP server has accepted the message for processing. Check provider logs or bounce reports if it does not arrive.

During local diagnosis, the SMTP debug stream shows the conversation between PHPMailer and the server. Keep that transcript inside a protected development environment because it can expose addresses and server details. Turn debugging off before production.

Do not concatenate untrusted form input into an HTML message without escaping it. Build the body from validated fields and encode text for the HTML context, or use the plain-text alternative when formatting adds no value.

Recipients in BCC do not see one another’s addresses. For attachments, use a server-side file path you control rather than a path supplied by a form submission.

For Unicode subjects and message text, keep the character set at UTF-8 as in the configuration above. This tells PHPMailer how to encode the message text.

PHPMailer Features, History, and Project Files

The repository’s latest commit and release history show when maintainers changed the code. Before using an older snippet, compare its class names and options with the current README and examples rather than assuming every tutorial matches the installed package.

  • composer.json is the dependency manifest. Review its require entry when changing the package set.
  • composer.lock records the resolved package versions for repeatable project installs.
  • vendor/ is generated project output. The application loads the generated autoloader from this directory.
  • PHPMailer src/ contains library classes. The examples/ folder gives concrete usage to compare with your integration.

PHPMailer SMTP Errors and Fixes

SMTP errors identify which part of the handoff failed, but the message alone may not identify the cause. Check the SMTP response alongside the host, network access, TLS mode and credential configuration.

SymptomCheckNext step
SMTP connect() failedHostname, port, outbound firewall policy and TLS modeConfirm the provider endpoint and test whether the application host can reach that port
Authentication failedUsername, secret and account authentication policyRotate or replace the secret through the provider’s approved credential flow
Could not instantiate mail functionWhether the code selected SMTP or PHP mail(), and whether local mail transport existsCall isSMTP() for SMTP delivery or configure the host’s local mail transport
Message accepted but absentRecipient spam folder, bounce notices and provider activity logCheck sender verification and delivery events, because SMTP acceptance is not inbox confirmation

For SMTP connect() failed, credentials may not have been checked yet because the client can fail before login. Verify DNS, the exact host and port, and outbound network rules first. Then compare the encryption setting with the provider’s documented connection type.

A mailbox password may not work when the SMTP service requires an app password or OAuth. Check the provider’s authentication method and confirm the account name. Never disable TLS verification to work around an error.

For OAuth-based application login, see CodeForGeek’s PHP OAuth 2.0 login guide. That flow is separate from SMTP authentication.

Use the official PHPMailer troubleshooting guide when the SMTP transcript points to a library or protocol issue. For a PHP transport issue, compare your setup with the PHP mail() documentation rather than assuming PHP configures a mail server by itself.

Conclusion: Keep SMTP Credentials Out of Code

Before connecting the feature to a contact form, verify the provider settings with a controlled test account and review the server response.

See CodeForGeek’s PHP tutorial resources for related PHP topics.

FAQ

These answers cover installation and the SMTP setup questions that commonly come with a first PHPMailer integration.

How do I install PHPMailer with Composer?

Run composer require phpmailer/phpmailer in your project directory, then load vendor/autoload.php in the PHP script.

Which SMTP port should PHPMailer use?

Use the host and port specified by your email provider. Port 587 commonly uses STARTTLS, while some services specify implicit TLS on port 465.

Does PHPMailer confirm that an email reached the inbox?

No. A successful send means the configured transport accepted the message. Check provider delivery events and bounce reports to determine what happened afterward.

Pankaj Kumar
Pankaj Kumar

Pankaj Kumar is the founder and CEO of CodeForGeek, with more than 14 years in IT. He is an open-source enthusiast who enjoys sharing what he learns through CodeForGeek and YouTube, with a focus on Python, data analytics, machine learning, Angular, Node.js, and Kafka.

Articles: 337