protected function get_imap_client() {
        global $CFG;

        if (!\core\message\inbound\manager::is_enabled()) {
            // E-mail processing not set up.
            mtrace("Inbound Message not fully configured - exiting early.");
            return false;
        }

        mtrace("Connecting to {$CFG->messageinbound_host} as {$CFG->messageinbound_hostuser}...");

        $configuration = array(
            'username' => $CFG->messageinbound_hostuser,
            'password' => $CFG->messageinbound_hostpass,
            'hostspec' => $CFG->messageinbound_host,
            'secure'   => $CFG->messageinbound_hostssl,
            'debug'    => empty($CFG->debugimap) ? null : fopen('php://stderr', 'w'),
        );

        if (strpos($configuration['hostspec'], ':')) {
            $hostdata = explode(':', $configuration['hostspec']);
            if (count($hostdata) === 2) {
                // A hostname in the format hostname:port has been provided.
                $configuration['hostspec'] = $hostdata[0];
                $configuration['port'] = $hostdata[1];
            }
        }

        $this->client = new \Horde_Imap_Client_Socket($configuration);

        try {
            $this->client->login();
            mtrace("Connection established.");

            // Ensure that mailboxes exist.
            $this->ensure_mailboxes_exist();

            return true;

        } catch (\Horde_Imap_Client_Exception $e) {
            $message = $e->getMessage();
            throw new \moodle_exception('imapconnectfailure', 'tool_messageinbound', '', null, $message);
        }
    }