The pineal gland is an endocrine gland, like the pituitary gland, thyroid gland, adrenal gland, and pancreas. Like other endocrine glands, it secretes a hormone -- in this case melatonin. The pineal gland was the last endocrine gland to have its function unveiled, partially because of its small size, roughly that of a pea, and its structural uniformity. It was not until the 1960s that scientists determined its function, having thought for several decades that it was merely a vestigial organ like the appendix.
Because of our relative ignorance about the pineal gland for so long, it became the object of mythical theories and attributions. Rene Descartes called it the "seat of the soul" because it appeared to be the only brain structure not composed of two symmetrical parts, although later analysis proved this to be untrue. Compounding these rumors was the fact that the pineal gland is lodged very deep in the brain, close to its center. Various shaman-types have claimed that the pineal gland secretes natural psychedelics and is somehow a connection between the earthly realm and a spirit world. These speculations are likely false.
In reality, the melatonin secreted by the pineal gland is responsible for various aspects of sexual development, animal hibernation, metabolism, and seasonal breeding. The gland secretes its hormone in sync with circadian rhythms, releasing more in the dark and less in the light. This probably contributes to minimize sexual thoughts while sleeping. In children, the pineal gland secretes more melatonin than in adults, which is said to inhibit sexual development. After puberty, the pineal gland shrinks and releases less melatonin.
The pineal gland is primarily composed of specialized cells called pinealocytes, which manufacture and secrete melatonin through capillaries. They also possess a distinct organelle called a synaptic ribbon, which can be used to identify pinealocytes. In animals, the pineal gland tends to be located closer to the surface of the brain, but over the course of evolution it migrated inwards.