Actions

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.

Contents

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' ) );
 
$mailer->setSender($sender);

Recipient

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

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

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

$recipient = array( 'person1@domain.com', 'person2@domain.com', 'person3@domain.com' );
 
$mailer->addRecipient($recipient);

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";
$mailer->setBody($body);

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>";
$mailer->isHTML(true);
$mailer->setBody($body);

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