$messagecontact = new \stdClass();
$messagecontact->userid = $student_id; // user
$messagecontact->contactid = $teacher->id; // user
$messagecontact->timecreated = time();
$messagecontact->id = $DB->insert_record('message_contacts', $messagecontact);
$eventparams = [
'objectid' => $messagecontact->id,
'userid' => $student_id,
'relateduserid' => $teacher->id,
'context' => \context_user::instance($student_id)
];
$event = \core\event\message_contact_added::create($eventparams);
$event->add_record_snapshot('message_contacts', $messagecontact);
$event->trigger();