Send Email through SMTP with PHPMailer

Last updated: August 29, 2026.

Authenticated SMTP provides a clear server, port, encryption mode, and error path. PHPMailer handles message formatting and protocol details more reliably than hand-built headers.

Configure SMTP

<?php
require __DIR__ . '/vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
$mail = new PHPMailer(true);
$mail->isSMTP(); $mail->Host = getenv('SMTP_HOST'); $mail->SMTPAuth = true;
$mail->Username = getenv('SMTP_USER'); $mail->Password = getenv('SMTP_PASSWORD');
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587;
$mail->setFrom('[email protected]', 'Example App');
$mail->addAddress('[email protected]');
$mail->Subject = 'Your report is ready'; $mail->Body = 'The report is available.';
$mail->send();

Match the provider settings

  • Use the exact host, port, and TLS mode supplied by the provider.
  • Keep credentials in a secret store or environment variables.
  • Do not disable certificate verification.
  • Catch exceptions and record a safe diagnostic.

Need email inside a database application?
PHPRunner can add notifications and email actions to generated PHP applications. Explore PHPRunner.

Test the complete delivery path

A successful SMTP transaction proves that a mail server accepted the message, not that it reached the inbox. Keep the provider message ID or server response so later bounces and delivery events can be correlated.

Test authentication failure, an invalid recipient, TLS negotiation, and a message to more than one provider. Protect diagnostic logs because they can contain addresses and server details.

  • Keep credentials outside source code.
  • Use the provider’s exact TLS mode.
  • Publish aligned SPF and DKIM records.

Keep resource limits explicit and make failure cleanup part of the example. Log enough context to diagnose the operation without recording passwords, private message bodies, or uploaded file contents.

Continue with existing PHP email guide, delivery troubleshooting, and queued delivery.

Reference: PHPMailer official repository.

admin

admin