How to send email from components
From Joomla! Documentation
This is an example of how to send an email from a component. You would typically put this into your components controller.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 sender of an email is set with setSender. The function takes an array with an email address and a name as an argument. We fetch the sites email address and name from the global 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
You set the recipient of an email with the function addRecipient. To set the email address to the currently logged in user, we fetch it from the user object.$user =& JFactory::getUser();
$recipient = $user->email;
$mailer->addRecipient($recipient);
$recipient = array( 'person1@domain.com', 'person2@domain.com', 'person3@domain.com' );
$mailer->addRecipient($recipient);
Create the mail
We need to set a subject line and create the text body. The subject is set with setSubject.The easy way to create an email body is as a string with plain text. Use the function setBody to add a message to the mail body. You can also attach a file with addAttachment. It takes a single file name or an array of file names as argument.
$body = "Your body string\nin double quotes if you want to parse the \nnewlines etc";
$mailer->setSubject('Your subject string');
$mailer->setBody($body);
// Optional file attached
$mailer->addAttachment(JPATH_COMPONENT.DS.'assets'.DS.'document.pdf');
$body = '<h2>Our mail</h2>'
. '<div>A message to our dear readers'
. '<img src="cid:logo_id" alt="logo"/></div>';
$mailer->isHTML(true);
$mailer->setBody($body);
// Optionally add embedded image
$mailer->AddEmbeddedImage( JPATH_COMPONENT.DS.'assets'.DS.'logo128.jpg', 'logo_id', 'logo.jpg', 'base64', 'image/jpeg' );
Sending the mail
The mail is sent with the function Send. It returns true on success or a JError object.$send =& $mailer->Send();
if ( $send !== true ) {
echo 'Error sending email: ' . $send->message;
} else {
echo 'Mail sent';
}
The JMail object is used for sending mail in Joomlas contact manager. See the file joomla/components/com_contact/controller.php
No comments:
Post a Comment