We evaluated the capacity of the Mycoplasma agalactiae p40 gene as a diagnostic marker for contagious agalactia in sheep by quantitative real-time PCR. The p40 gene encodes an immunodominant adhesin that plays a key role in cytoadhesion of M. agalactiae. The assay was 100% specific, with an analytical sensitivity of 1 genome equivalent (GE), a quantification that is highly linear (R(2) > 0.992) and efficient (PCR efficiency, >0.992) over a 6-log dynamic range, down to 10 GE. We evaluated the capacity of the assay to detect Mycoplasma agalactiae in 797 milk samples (373 raw sheep milk samples from refrigerated tanks of different farms and 424 milk samples from individual sheep of a flock positive for M. agalactiae). In parallel, we also tested the samples by using microbiological isolation coupled with microscopy identification and by a PCR method recommended by the World Organization for Animal Health. While our assay was able to detect 57 (15.28%) positive samples of the 373 milk samples from different farms, identification by microbiological isolation coupled with microscopy detected only 36 (9.65%) samples, and the conventional PCR detected 31 (8.31%) samples. These findings showed that our assay based on the p40 gene is more specific and sensitive for the detection of M. agalactiae in actual natural samples and, thus, can be a promising alternative tool for diagnosis and epidemiological studies of M. agalactiae infection.