- 
            - How to Add a User to a Joomla Group Programmatically
- How to Send Emails in Joomla with PHP
- How to Connect to an External Database in Joomla with PHP
- How to Check if the Current Page Is the Homepage in Joomla with PHP
- How to Check If the Current User is Super User in Joomla with PHP
- How to Create a User Account in Joomla with PHP
- How to Create an Article in Joomla with PHP
- PHP Scripts Collection
 
How to Send Emails in Joomla with PHP
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;
// Load the Joomla mailer class
$mailer = Factory::getMailer();
// 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 Nov 28th 2024 18:11        
     
            