Sending email from extensions

From Joomla! Documentation

Revision as of 06:58, 21 January 2010 by Hasse bjork (Talk | contribs)

This is an example of how to send an email from a component. You would typically put this into your components controller.

Fetch the mail object

A reference to the global mail object (JMail) is fetched through the JFactory object. This is the object creating our mail.

$mailer =& JFactory::getMailer();

Set a sender

The mailer expect the sender to be an array of an email address and a name. We fetch the sites email address and name from the configuration. These are set in the administration back-end (Global Configuration -> Server -> Mail Settings).

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


The currently logged in users email address is stored in the user object.

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

If we had multiple recipients we would put each recipients email in an array.

$recipient = array( '', '', '' );

Create the mail

We need to set a mail subject and create the body of the mail. The subject is easy to set using the mailer object

$mailer->setSubject('Your subject string');

The body is a text string of your choice set with the setBody function.

$body   = "Your body string\nin double quotes if you want to parse the \nnewlines etc";

If you prefer an email formatted in HTML, you need to tell the mailer it is html.

$body   = "<h2>Our mail</h2><div>A message to our dear readers</div>";

Sending the mail

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

You would probably want to write your own error handler, if there is an error sending the mail.

The JMail object is used for sending mail in Joomlas contact manager. See the file joomla/components/com_contact/controller.php

See also