Shortcode to generate and save password in a file

I have the following shortcode:

// Add Shortcode
function custom_shortcode_phptest() {

  function generatePassword($length = 6) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$pass = '';
for ($i = 0; $i < $length; $i++) {
$pass .= $characters[rand(0, $charactersLength - 1)];
}
return $pass;
}

$password = generatePassword();

$data = time();

$test = '/home/blablabla/public_html/ot/docs/test/' . $password . '.txt';
$file = fopen($test,"w");
fwrite($file,$data);
fclose($file);
echo 'Your pass is ' . $password . ' and it is valid for 3 days.';

}
add_shortcode( 'phptest', 'custom_shortcode_phptest' );

It will generate a password and save it in a file. But when I use [phptest] shortcode in email, sent from WordPress admin panel it doesn’t work. Is it okay to use function inside function in php shortcode?

Solutions Collecting From Web of "Shortcode to generate and save password in a file"

Per the comment under the OP’s question, below is the solution by using a return instead of an echo:

add_shortcode( 'phptest', 'custom_shortcode_phptest' );
function custom_shortcode_phptest() { // Add Shortcode

    function generatePassword( $length = 6 ) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen( $characters );
        $pass = '';
        for ( $i = 0; $i < $length; $i++ ) {
            $pass .= $characters[rand( 0, $charactersLength - 1 )];
        }
        return $pass;
    }

    $password = generatePassword();

    $data = time();

    $test = '/home/blablabla/public_html/ot/docs/test/' . $password . '.txt';
    $file = fopen( $test, "w" );
    fwrite( $file, $data );
    fclose( $file );
    return 'Your pass is ' . $password . ' and it is valid for 3 days.';
}