Sending an email from any Joomla extension is straight forward process. You can put this code into your component's controller file or module's helper file.
For sending email, you need minimum four things:
First, you have to fetch the mail object.
$mailer = JFactory::getMailer();
The sender of an email is set with setSender function. It takes an array with an email address and a name as an argument. We will be accessing this information from Global Configuration.
$config = JFactory::getConfig();
$sender = array(
$config->get( 'mailfrom' ),
$config->get( 'fromname' )
);
$mailer->setSender($sender);
The recipient of an email is set with the function addRecipient. We will be accessing this data from User information.
$user = JFactory::getUser();
$recipient = $user->email;
$mailer->addRecipient($recipient);
The subject is set with setSubject function.
$mailer->setSubject('Email Subject Line');
You can use the function setBody to add a message to the mail body.
$body = 'Email message body';
$mailer->setBody($body);
The last part is to send email with the function Send. It returns true on success or a JError object.
$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.
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');
If you want to format your email in HTML, you need to tell the mailer 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';
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' );
The JMail object is used for sending mail in Joomla's contact component. You can check the file at:
joomla/components/com_contact/controller.php