Well i just set "$message->courseid = $course_id" and it seems to have solved the error.
Thank you for the help
General help
$PAGE context error when trying to send message
This discussion has been locked so you can no longer reply to it.