PHP's built-in mail() function hands messages to the local sendmail binary without SMTP authentication, TLS negotiation, or structured error reporting. PHPMailer adds an SMTP client, MIME formatting, and attachment support to PHP applications.
How do you install PHPMailer?
Use Composer:
composer require phpmailer/phpmailer
Then load the autoloader and import the classes you need:
<?php
require "vendor/autoload.php";
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
How do you configure SMTP and send a message?
Create a PHPMailer instance, switch it into SMTP mode with isSMTP(), then set the connection and message fields. Wrap the call in try/catch so a failed send is reported rather than swallowed:
<?php
$mail = new PHPMailer(true); // true enables exceptions
try {
// Server settings
$mail->isSMTP();
$mail->Host = "smtp.example.com";
$mail->SMTPAuth = true;
$mail->Username = getenv("SMTP_USER");
$mail->Password = getenv("SMTP_PASS");
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
// Recipients
$mail->setFrom("you@yourdomain.com", "Your App");
$mail->addAddress("recipient@example.org", "Recipient Name");
// Content
$mail->isHTML(true);
$mail->Subject = "Your receipt";
$mail->Body = "<p>Thanks for your order.</p>";
$mail->AltBody = "Thanks for your order. This is the plain-text version.";
$mail->send();
echo "Message sent.";
} catch (Exception $e) {
echo "Send failed: {$mail->ErrorInfo}";
}
Match SMTPSecure to your server's port: ENCRYPTION_STARTTLS on port 587 upgrades a cleartext connection to TLS, and ENCRYPTION_SMTPS on port 465 negotiates TLS immediately. Setting isHTML(true) marks Body as HTML and includes AltBody as the plain-text part for clients that do not render HTML. Including both parts also improves deliverability. Passing true to the constructor makes failures throw an Exception instead of returning false.
How do you add an attachment?
Call addAttachment with a file path before send():
<?php
$mail->addAttachment("./invoices/invoice-1042.pdf", "invoice.pdf");
The second argument renames the file as the recipient sees it. You can call it more than once for multiple attachments.
Send it with Bird
To send email from PHP over HTTPS without managing an SMTP connection, install the Bird PHP SDK (composer require messagebird/sdk) and call $bird->email->send():
<?php
use MessageBird\Bird;
$bird = new Bird(apiKey: getenv("BIRD_API_KEY"));
$message = $bird->email->send(
from: "onboarding@messagebird.dev",
to: ["delivered@messagebird.dev"],
subject: "Hello from PHP",
html: "<p>It works.</p>",
);
echo $message->getId(), " ", $message->getStatus(), "\n";
The onboarding@messagebird.dev sender and delivered@messagebird.dev sandbox recipient verify your API key and payload before you configure a custom domain.