Torah law forbids milking a cow or any other animal on Shabbat, as doing so separates the milk from the cow’s body and constitutes Mefarek (separating something from its source), a tolada of Dash. Just as one may not separate grain from its husk, so too, one may not separate milk from its source (Shabbat 95a).
The problem is that if a dairy cow, which produces great quantities of milk, is not milked on Shabbat, it suffers greatly. Therefore, the Sages permitted asking a non-Jew to milk a cow on Shabbat. Even though, generally speaking, it is rabbinically prohibited to ask a non-Jew to do melakha for us on Shabbat, here they suspended the prohibition in order to avoid tza’ar ba’alei ĥayim. It is true that this milk is muktzeh on Shabbat. However, after Shabbat a Jew may drink or sell it (SA 305:20).
If there is no non-Jew available, a Jew may milk the cow, as long as the milk goes to waste. For example, it may be milked directly onto the ground, or into a bucket that contains an agent that will ruin the milk. This is because milking to make use of the milk is prohibited by Torah law, whereas milking for another reason, in which the milk goes to waste, is only rabbinically prohibited. A Torah prohibition may not be transgressed in order to prevent animals’ suffering, but the Sages suspended their own enactment.
Nowadays, dairy farming has been modernized, and milking is automated. A cup is placed on the teat and connected to a pump via a tube. If there is a non-Jew available, one may ask him to turn on the machine and place the cups on the cow on Shabbat, because otherwise the cows would suffer. If no non-Jew is available, common practice is for a Jew to use a timer or a delay mechanism that is set before Shabbat to turn on the machine. On Shabbat, before the machine turns on, the cups are attached to the cow’s teats, and then the machine turns on and automatically pumps out the milk. Thus, the Jew has not performed any melakha directly, for when he attached the cups, the machine was not on. Even though placing the cups on the teats causes a melakha to take place, this is not prohibited by Torah law. The Torah only forbids direct action, as it states: “You shall not do any melakha” (Shemot 20:10). The Sages forbade indirectly causing a melakha to be performed. Here, to prevent the cows from becoming painfully engorged, the Sages permitted acting via grama. After Shabbat, a Jew may benefit from this milk.
If the cups must be attached to the teats while the machine is operating, then doing so in order to save the milk violates Torah law. Therefore, the milk should spill directly onto the ground, making the action rabbinically prohibited and thus permissible to prevent tza’ar ba’alei ĥayim (SSK 27:50; for the laws relevant to a woman who is engorged, see above 11:17).