public static function send_confirm_link_login_email($userinfo, $issuer, $userid) {
        $record = new stdClass();
        $record->issuerid = $issuer->get('id');
        $record->username = $userinfo['username'];
        $record->userid = $userid;
        if (linked_login::has_existing_issuer_match($issuer, $userinfo['username'])) {
            throw new moodle_exception('alreadylinked', 'auth_oauth2');
        }
        $record->email = $userinfo['email'];
        $record->confirmtoken = random_string(32);
        $expires = new \DateTime('NOW');
        $expires->add(new \DateInterval('PT30M'));
        $record->confirmtokenexpires = $expires->getTimestamp();

        $linkedlogin = new linked_login(0, $record);
        $linkedlogin->create();

        // Construct the email.
        $site = get_site();
        $supportuser = \core_user::get_support_user();
        $user = get_complete_user_data('id', $userid);

        $data = new stdClass();
        $data->fullname = fullname($user);
        $data->sitename  = format_string($site->fullname);
        $data->admin     = generate_email_signoff();
        $data->issuername = format_string($issuer->get('name'));
        $data->linkedemail = format_string($linkedlogin->get('email'));

        $subject = get_string('confirmlinkedloginemailsubject', 'auth_oauth2', format_string($site->fullname));

        $params = [
            'token' => $linkedlogin->get('confirmtoken'),
            'userid' => $userid,
            'username' => $userinfo['username'],
            'issuerid' => $issuer->get('id'),
        ];
        $confirmationurl = new moodle_url('/auth/oauth2/confirm-linkedlogin.php', $params);

        $data->link = $confirmationurl->out(false);
        $message = get_string('confirmlinkedloginemail', 'auth_oauth2', $data);

        $data->link = $confirmationurl->out();
        $messagehtml = text_to_html(get_string('confirmlinkedloginemail', 'auth_oauth2', $data), false, false, true);

        $user->mailformat = 1;  // Always send HTML version as well.

        // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
        return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
    }