JOOMLA FICTION LAB
(3 votes)

How to send email from a Joomla component

Friday, 26 August 2011 12:21
Sending email notifications to users is a very important feature that every Joomla component should have.

The Joomla API makes this very easy with the JMail class.
You can learn more about the JMail class here.

Usage


1. The global mail object (JMail) is fetched through the JFactory object:
$mailer =& JFactory::getMailer();

2. We set the sender of the email with the function setSender. The site email address and name are fetched from the global configuration:
$config =& JFactory::getConfig();
$sender = array( 
    $config->getValue( 'config.mailfrom' ),
    $config->getValue( 'config.fromname' ) );
$mailer->setSender($sender);

3. The recipient is set with the function addRecipient.
$recipient = 'recipient@domain.com';
$mailer->addRecipient($recipient);

For multiple recipients you can use an array:
$recipient = array( 'recipient1@domain.com', 'recipient2@domain.com', 'recipient3@domain.com' );
$mailer->addRecipient($recipient);

4. The subject is set with the function setSubject. You can add a message to the mail body with the function setBody. If you want to attach a file you can use the function addAttachment:
$body   = "The body string";
$mailer->setSubject('The subject string');
$mailer->setBody($body);
// Optionally attach a file
$mailer->addAttachment(JPATH_COMPONENT.DS.'assets'.DS.'attachment.zip');

Optionally you can format your email in HTML using the function IsHTML. If you want to embed an image you can use the function AddEmbeddedImage:
$body   = '<h2>The email</h2>'
    . '<div>The message string'
    . '<img src="cid:logo_id" alt="logo"/></div>';
$mailer->isHTML(true);
$mailer->Encoding = 'base64';
$mailer->setBody($body);
// Optionally embed an image
$mailer->AddEmbeddedImage( JPATH_COMPONENT.DS.'assets'.DS.'logo128.jpg', 'logo_id', 'logo.jpg', 'base64', 'image/jpeg' );

5. Finally you can send the email with the function Send:
$send =& $mailer->Send();
if ( $send !== true ) {
    echo 'Error sending email: ' . $send->message;
} else {
    echo 'Mail sent';
}




Add comment


Security code
Refresh