Sending Email From Joomla Platform Using Mailer

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

The Joomla Mail Class extends PHPMailer Class.

For sending email, you need at least four things:

  1. Sender email and name (setSender)
  2. Recipient email (addRecipient)
  3. Subject Line (setSubject)
  4. Body (setBody)

First, you have to fetch the mail object.

$mailer = Factory::getMailer();

1. Sender

The sender of an email is set with setSender() method. It takes an array as argument with an email address and a name. You can get this information from Global Configuration.

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

$mailer->setSender($sender);

2. Recipient

The recipient of an email is set with the addRecipient() method. You can get this data from User information.

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

$mailer->addRecipient($recipient);

3. Subject Line

The subject is set with setSubject() method.

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

4. Body of Email

You can use the setBody() method to add a message to the mail body.

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

5. Sending the Mail

The last part is to send email with the Send() method.

$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.

6. File Attachments

You can attach a file with addAttachment. It takes a single file name or an array of file names as the argument.

$mailer->addAttachment(JPATH_COMPONENT.'/assets/document.pdf');

7. HTML Emails

If you want to format your email in HTML, you need to tell the mailer that it is HTML. When sending HTML emails you should normally set the encoding to base64 in order to avoid unwanted characters in the output.

$mailer->isHtml(true);
$mailer->Encoding = 'base64';

8. Embedding Images

You should leave any images on your server and refer to them with HTML image tag, to reduce size of the mail and the time sending it.

$body = '<h2>Our mail</h2>'
. '<div>A message to our dear readers'
. '<img src="cid:logo_id" alt="logo"/></div>';

$mailer->AddEmbeddedImage(JPATH_COMPONENT.'/assets/logo128.jpg', 'logo_id', 'logo.jpg', 'base64', 'image/jpeg');

9. Reply To

You can add Reply to email address to the email using addReplyTo() method.

$mailer->addReplyTo($replyto);

The $replyto can be a single email or array of emails.