During the last three decades, many papers have reported the existence of a luminosity-metallicity or mass-metallicity (M-Z) relation for all kinds of galaxies: The more massive galaxies are also the ones with more metal-rich interstellar medium. We have obtained the mass-metallicity relation at different lookback times for the same set of galaxies from the Sloan Digital Sky Survey (SDSS), using the stellar metallicities estimated with our spectral synthesis code STARLIGHT. Using stellar metallicities has several advantages: We are free of the biases that affect the calibration of nebular metallicities; we can include in our study objects for which the nebular metallicity cannot be measured, such as AGN hosts and passive galaxies; we can probe metallicities at different epochs of a galaxy evolution. We have found that the M-Z relation steepens and spans a wider range in both mass and metallicity at higher redshifts for SDSS galaxies. We also have modeled the time evolution of stellar metallicity with a closed-box chemical evolution model, for galaxies of different types and masses. Our results suggest that the M-Z relation for galaxies with present-day stellar masses down to 10^10 solar masses is mainly driven by the star formation history and not by inflows or outflows.