Pretty simple. Its basically the same as the little sensor they have installed in the doors of small businesses, that make the door bell ring.
amazon.com/OWSOO-Electric-Magnetic-Electromagnet-Fail-Safe