The reason why snails bubble or foam when picked up or touched is due to a defense mechanism the snail has naturally built in.
The snail produces that foam to defend against threats to it when it feels threatened so the snail foams or bubbles so that you will put the snail down.
Some other predators in the wild will leave the snail alone when it starts to bubble because if the snail is getting eaten the predator will usually spit the snail out and leave it alone once it starts bubbling or foaming.
It's just a way for the small snail to defend itself.