How to Send Emails in Joomla with PHP

Heads up! This article contains PHP code and is intended for developers. We offer this code as a courtesy, but don't provide support for code customizations or 3rd party development.

Sending emails in Joomla using PHP involves leveraging Joomla's built-in mailer class. This ensures seamless integration with Joomla's configuration and supports HTML and plain-text emails. Below is a step-by-step guide to sending emails in Joomla, including code improvements and explanations.


use Joomla\CMS\Factory;
use Joomla\CMS\Mail\MailerFactoryInterface;
  
// Load the Joomla mailer class
$mailer = Factory::getContainer()→get(MailerFactoryInterface::class)→createMailer();

// Define necessary variables
$sender_email = '[email protected]';
$sender_name  = 'Your Name';
$recipient    = '[email protected]';
$subject      = 'Your Subject Here'; 
$body         = 'This is the content of your email';

// Set mail sender (array with email and name)
$mailer→setSender([
    $sender_email,
    $sender_name
]);

// Set recipient, subject, and body of the email
$mailer
    →addRecipient($recipient)
    →isHTML(true) 
    →setSubject($subject)
    →setBody($body);

// Set plain text alternative body (for email clients that don't support HTML)
$mailer→AltBody = strip_tags($body);

// Send the email and check for success or failure
try {
    $send = $mailer→Send(); // Attempt to send the email
    
    if ($send !== true) {
        echo 'Error: ' . $send→__toString(); // Display error message if sending fails
    } else {
        echo 'Email sent successfully!';
    }
} catch (Exception $e) {
    echo 'Mail error: ' . $e→getMessage(); // Catch and display any exceptions
}
Last updated on Feb 26th 2026 15:02