I did a little research. The ink sac is indeed attached near to the anus. It's thought to be an evolution of the hypobranchial gland still present in many mollusks, and the mucus-producing funnel gland that it works alongside may have originally been used to trap and excrete dirt particles when breathing through the gills - I guess very similarly to mammalian mucus in the respiratory system. It's used in conjunction with jet propulsion for distribution of the ink.
We're not sure what the use of the melanin that makes ink black was (it's kept it's current form in cephalopods for at least 300 million years) but it may have been a waste product from use in the body for camouflage or adjusting photosensitivity.