"It is believed that the mammary gland is a transformed sweat gland, more closely related to Apocrine sweat glands. There are many theories of how they evolved, but since they do not fossilize well, supporting such theories is difficult. Many of the current theories are based on comparisons between lines of living mammals- monotremes, marsupials and eutherians. One theory proposes that mammary glands evolved from glands that were used to keep the eggs of early mammals moist and free from infection (monotremes still lay eggs). Other theories propose that early secretions were used directly by hatched young, or that the secretions were used by young to help them orient to their mothers.
Lactation developed long before the evolution of the mammary gland and mammals, see evolution of lactation."
Wikipedia is your friend.