How To Send Email from Your Joomla Extension
Because of it ubiquitous nature, automatic emailing is something that many clients expect. People 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! already provides some of this functionality out of the box by notifying administrators when a user has registered on their site. You, however, may find yourself needing to implement emailing in your own components. As you may have already guessed, Joomla! provides a very helpful class for this: JMail.
With just a few lines of code, you can send your first email:
$to = "email@example.com";
$from = array("firstname.lastname@example.org", "Brian Edgerton");
# Invoke JMail Class
$mailer = JFactory::getMailer();
# Set sender array so that my name will show up neatly in your inbox
# Add a recipient -- this can be a single address (string) or an array of addresses
# If you would like to send as HTML, include this line; otherwise, leave it out
# Send once you have set all of your options
That's all there is to it for sending a simple email. If you would like to add carbon copy recipients, include the following before sending the email:
# Add a blind carbon copy
Need to add an attachment? No problem:
As you can see, it really can't get much simpler or straightforward for sending an email. 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. Consider the following:
Next time your client requests email alerts when someone fills out your custom form, don't panic. JMail has done all the hard work for you. Figure what information is going to be sent, and use these few lines of code send it via email.