Sending an email from any Joomla extension is straight forward process. You can put this code into your component's controller file or module's helper file.

For sending email, you need minimum 4 items:

  1. Sender (email and name)
  2. Recipient (email)
  3. Subject Line
  4. Body

First, you have to fetch the mail object.

$mailer = JFactory::getMailer();

Sender

The sender of an email is set with setSender function. It takes an array with an email address and a name as an argument. We will be accessing this information from Global Configuration.

$config = JFactory::getConfig();
$sender = array(
$config->get( 'mailfrom' ),
$config->get( 'fromname' )
);

$mailer->setSender($sender);

Recipient

The recipient of an email is set with the function addRecipient. We will be accessing this data from User information.

$user = JFactory::getUser();
$recipient = $user->email;

$mailer->addRecipient($recipient);

Subject Line

The subject is set with setSubject function.

$mailer->setSubject('Email Subject Line');

Body of Email

You can use the function setBody to add a message to the mail body.

$body = 'Email message body';
$mailer->setBody($body);

Sending the Mail

The last part is to send email with the function Send. It returns true on success or a JError object.

$send = $mailer->Send();
if ( $send !== true ) {
echo 'Error sending email: ' . $send->__toString();
} else {
echo 'Mail sent';
}

Check your inbox, you should have received your email.