Moodle Email Function Not Working

1.8k Views Asked by At

Hi i want to send an email as soon as record is inserted in moodle database table, following code is not working

if ($recs = $ti_form->get_data()) {
    // Do something with the data, then redirect to a new page
    $lastinsertid = $DB->insert_record('suggestions', $recs);
    $toUser = '[email protected]';
    $fromUser = 'ICAN';
    $subject = 'New Suggestion Added';
    $messageText = 'New Suggestion Added';
    $sent = email_to_user($toUser, $fromUser, $subject, $messageText);
    //mail($to, $subject, $message, $headers);

    if($sent) {
      print "Email successfully sent";
    }else{
      print "There was an error sending the mail";
     }

       redirect('suggestions.php');
}

Above code givers error message. What could be the reason? Any help much appreciated.

Thanks

2

There are 2 best solutions below

0
On BEST ANSWER

If you look at the phpdoc header for the email_to_user() function, the first 2 parameters should be user objects rather than strings.

* @param stdClass $user  A {@link $USER} object
* @param stdClass $from A {@link $USER} object

So for the to user

$touser = $DB->get_record('user', array('email' => '[email protected]');

For the from user you could use the support user

$fromuser = core_user::get_support_user();
0
On

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:

  1. Click Site Administration > Advanced Features > Development > Debugging
  2. Set Debug messages to DEVELOPER: extra Moodle debug messages for developers
  3. Check the Display debug messages box.
  4. Check the Debug email sending box.
  5. Click Save changes at the bottom of the page.

Don't forget to go back and disable these settings when you are done debugging.

Debug your work, this will show you some outputs which it can be helpful for your problem.