Using the Joomla JMail Class

  • PDF

JMail Class Introduction

The JMail class can be used to add email capability to your Joomla! website.  JMail is an extension of the PHPMailer class so contains all the methods and attributes available to this class.

To the JMail class in your file you will need to include the class file, like this:

jimport( 'joomla.mail.mail' );
 

You will then need to instantiate a mail object, this can be done like this:

$mail =& JMail::getInstance();
 

Next you can create an email by calling the email methods available from the class, review the class information at this link, http://api.joomla.org/Joomla-Framework/Mail/JMail.html.

Exercise

In class extend your Guestbook component so that it sends an email to the person filling out the form.  You will need to include a sender, address, subject line and the body of the email.  Then send the email.

There is a bit of a trick with setting the sender - the function can take an array to set the email address and the email name.  You can do it this way:

  $sender[0] = 'myemail@gmail.com';
  $sender[1] = 'My Name - GMail';
  $mail->setSender( $sender );
 

Send HTML EMails

By default JMail sends text emails.  To send an HTML email see the following example:

$body ='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Title of the document</title>
</head>
You have posted the following to the guestbook: <br/>' . $msg .
'<body>
The content of the document......
</body>
 
</html>';
 
$mail->isHTML( TRUE );
$mail->setBody ( $body );
 

Include the HTML header information in your body text and then use the isHTML function to tell JMail that the email is in HTML format.

jimport vs. JFactory

Why is the JMail library loaded with jimport and not JFactory?  This is a good question and one that does not have a ready answer out on the web - if you see a summary anywhere please point me in the right direction.

Fortunately JFactory does have a good list of classes loaded with this class - http://docs.joomla.org/JFactory.