Monday, November 15, 2010

How to send email from your joomla component

Many times you will have the need to send emails from your joomla component. Users want to be notified immediately of changes on their sites, when a new article has been submitted, or a blog comment has been posted. Joomla provides email notifications to site administrator when a user has registered on their site.If you want to create a component and that component needs an email functionality, you dont need to create a custom email function for the component. Joomla provides a very helpful class for this.Thats JMail.


# Set the variables for the email message
$subject = "Subject for the email message";
$body = "Body of the email message";
$to = "user@domainname.com";
$from = array("admin@domainname.com", "Administrator");


# Invoke JMail Class

$mailSender = JFactory::getMailer();

# Set the sender array
$mailSender->setSender($from);

# Add the recipient - We can assign a single email address or an array of addresses

$mailSender->addRecipient($to);
$mailSender->setSubject($subject);
$mailSender->setBody($body);

# If you would like to send as HTML, include this line.
$mailSender->isHTML();
# Send the mail
if (!$mailSender ->Send())
{
echo "there is an error with the mail";
}


That's all for sending a simple email.If you would like to add carbon copy recipients, include the following before sending the email.



$mailSender->addCC("carboncopy@domainname.com");

# Add a blind carbon copy

$mailSender->addBCC("blindcopy@domainname.com");


It also has the option to add attachments.


If the file is in the server we can give the path.


$file = JPATH_SITE."/path/filename.doc";


$mailSender->addAttachment($file);


If we want to send an user uploaded file, then we have to give the option to upload the file.

The code is as follows.



Change the enctype of the form.


<form action="index.php" enctype="multipart/form-data" method="post" name="adminForm">

Add a file field within the form.



<input class="text_area" id="attachment" maxlength="250" name="attachment" size="32" type="file">









get the attached file.




$attachment = JRequest::getVar('attachment', null, 'files', 'array' );



$name_of_uploaded_file = $attachment['name'];
$config =& JFactory::getConfig();
$upload_folder = $config->getValue('config.tmp_path').DS;
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $attachment ['tmp_name'];

jimport('joomla.filesystem.file');
$uploaded = JFile::upload($tmp_path, $path_of_uploaded_file);
$mailSender->addAttachment($path_of_uploaded_file);






There are several more methods available in JMail.

You should also check out JMailHelper.

It provides several functions to help you secure input from users before passing it along in an email.

No comments:

Post a Comment