Connection to Photoelectric sensor

From this, if this matches the model which you are referring to, it appears that it can be mains powered (blue and brown wires).
Check very carefully that this is your model before connecting mains to it. If you have a 12v DC source, that would be safer.

The white wire is connected to the Mega's GND
The black wire is connected to a digital input pin (you choose this - say pin 3 )
The gray wire is not connected.

In your sketch you enable the built-in pull up resistor example: pinMode( 3, INPUT_PULLUP )