The role of cold gas and environment on the stellar mass-metallicity relation of nearby galaxies