General developer forum

$PAGE->context error when calling email_to_user()

Picture of Elliott Benzle
$PAGE->context error when calling email_to_user()

I'm trying to send an email during the scheduled task of a module I'm building and continue to get an error:

Coding problem: $PAGE->context was not set. You may have forgotten to call require_login() or $PAGE->set_context(). The page may not display correctly as a result

  • line 493 of /lib/pagelib.php: call to debugging()
  • line 820 of /lib/pagelib.php: call to moodle_page->magic_get_context()
  • line 1432 of /lib/weblib.php: call to moodle_page->__get()
  • line 5878 of /lib/moodlelib.php: call to format_string()
  • line 58 of /mod/ojt/classes/task/notify.php: call to email_to_user()
  • line 105 of /lib/cronlib.php: call to mod_ojt\task\notify->execute()
  • line 297 of /lib/cronlib.php: call to cron_run_inner_scheduled_task()
  • line 91 of /admin/tool/task/schedule_task.php: call to cron_run_single_task()

I've looked at other plugins and can't figure out what's wrong. This is running as a scheduled task so I'm confused why I need to set the context for the page. Could someone offer some advice on what I'm doing wrong?

My code looks like this:

namespace mod_ojt\task;

defined('MOODLE_INTERNAL') || die();

class notify extends \core\task\scheduled_task {

public function get_name() {

        // Shown in admin screens

        return get_string('notifytask', 'mod_ojt');


public function execute() {       

                global $DB, $CFG, $PAGE, $SITE;

require_once($CFG->dirroot . '/config.php');

$toUserId = 2;

$toUser = $DB->get_record('user', array('id' => $toUserId));

$fromUserId = 5;

$fromUser = $DB->get_record('user', array('id' => $fromUserId));

$subject = "OJT Approval Needed";

$messageText = "Test";

$messageHtml = "Test";

email_to_user($toUser, $fromUser, $subject, $messageText, $messageHtml);


} // end of class notify

Average of ratings: -
Picture of Sam Chaffee
Re: $PAGE->context error when calling email_to_user()
Core developers

Hi Elliot,

What version of Moodle are you using? I don't see anything in your code that would cause the problems you are seeing, but I would say that you don't need any of the globals except $DB since you use that directly. You also don't need to include config.php as it's already been done at that point.

It would be interesting to see if running the core send_failed_login_notifications task also causes the same issue because it also uses email_to_user.

Also, how are you testing running the task? It looks like you running the single task from the UI? What happens when you run the single task from the command line using the admin/tool/task/cli/schedule_task.php?

Average of ratings: -