Living in greener areas, or close to green and blue spaces (GBS; eg, parks, lakes, or beaches), is associated with better mental health, but longitudinal evidence when GBS exposures precede outcomes is less available. We aimed to analyse the effect of living in or moving to areas with more green space or better access to GBS on subsequent adult mental health over time, while explicitly considering health inequalities. A cohort of the people in Wales, UK (≥16 years; n=2 341 591) was constructed from electronic health record data sources from Jan 1, 2008 to Oct 31, 2019, comprising 19 141 896 person-years of follow-up. Household ambient greenness (Enhanced Vegetation Index [EVI]), access to GBS (counts, distance to nearest), and common mental health disorders (CMD, based on a validated algorithm combining current diagnoses or symptoms of anxiety or depression [treated or untreated in the preceding 1-year period], or treatment of historical diagnoses from before the current cohort [up to 8 years previously, to 2000], where diagnosis preceded treatment) were record-linked. Cumulative exposure values were created for each adult, censoring for CMD, migration out of Wales, death, or end of cohort. Exposure and CMD associations were evaluated using multivariate logistic regression, stratified by area-level deprivation. After adjustment, exposure to greater ambient greenness over time (+0·1 increased EVI on a 0-1 scale) was associated with lower odds of subsequent CMD (adjusted odds ratio 0·80, 95% CI 0·80-0·81), where CMD was based on a combination of current diagnoses or symptoms (treated or untreated in the preceding 1-year period), or treatments. Ten percentile points more access to GBS was associated with lower odds of a later CMD (0·93, 0·93-0·93). Every additional 360 m to the nearest GBS was associated with higher odds of CMD (1·05, 1·04-1·05). We found that positive effects of GBS on mental health appeared to be greater in more deprived quintiles. Ambient exposure is associated with the greatest reduced risk of CMD, particularly for those who live in deprived communities. These findings support authorities responsible for GBS, who are attempting to engage planners and policy makers, to ensure GBS meets residents' needs. National Institute for Health and Care Research Public Health Research programme.