You can send custom emails from within Moodle using PHP using your own forms using the email_to_user() function. By the way, did you know that Moodle actually uses the open source PHPMailer behind the scenes?
A typical call to Moodle's email_to_user() function would look like:
email_to_user($toUser, $fromUser, $subject, $messageText, $messageHtml, ", ", true);
This is a very simple version of a very powerful function. For more information about the email_to_user() function, take a look at the source code for function email_to_user in Moodle's /lib/moodlelib.php.
Tips for Using email_to_user()
- $toUser and $fromUser must be Moodle user objects, not email addresses. The stdClass object must contain a minimum of the following:
- $emailuser->email: Email address
- $emailuser->firstname: You can put both first and last name in this field.
- $emailuser->maildisplay = true;
- $emailuser->mailformat = 1; // 0 (zero) text-only emails, 1 (one) for HTML/Text emails.
- $emailuser->id: Moodle User ID. If it is for someone who is not a Moodle user, use an invalid ID like -99.
- Except for those fields above that have a description beside them, the rest of the fields can be set to an empty string if you don't have the information available.
- You can convert your HTML message into plain text using:
$messagetext = html_to_text($messagehtml);
- You can get the configured support user information using the following two variables:
- If you want the email to come from firstname.lastname@example.org, set the true parameter to false .
Be sure to always use Moodle filters to clean any user entered information before submitting it in an email including email addresses, subject, message or you will be just asking for trouble.
Enabling Email Debugging in Moodle
When developing email support in your Moodle plugin, you can make your life a whole lot easier by enabling email debugging however this should only be done in a development environment. The settings are all in the same place you would normally go to put Moodle debugging in DEVELOPER mode. Simply complete the following steps:
- Click Site Administration > Advanced Features > Development > Debugging
- Set Debug messages to DEVELOPER: extra Moodle debug messages for developers
- Check the Display debug messages box.
- Check the Debug email sending box.
- Click Save changes at the bottom of the page.
Don't forget to go back and disable these settings when you are done debugging.