Touching a tooth filling with a piece of silver foil was a famous experiment first performed by Luigi Galvani in 1762.
When two dissimilar metals are separated by a conducting liquid, a current will flow between them, and this current can be used to stimulate nerves.
This is exactly what happens when silver foil appears to touch the amalgam of a filling.
A thin film of saliva actually separates foil from filling, and because saliva is a reasonable electrolyte, containing various salts, a current will flow between the tooth and the filling.
As the filling is close to the dental nerve, the current will stimulate it, causing pain.
Galvani carried out his experiment with frogs’ legs and metal probes, but the effect was the same, they twitched as though they were alive.