Why are resistors necessary in the following circuit?
R2 is necessary to make sure that the mosfet M1 is in cutoff even if nothing is driving the GPIO12 line. This is important during power-up, for example, at which time the MCU in this system may not be driving GPIO12. If this resistor were absent, the mosfet might turn on during startup and engage the relay erroneously.
R1 is not necessary because M1 is a FET. Were M1 a BJT and not a MOSFET, then this resistor would limit the current into the base. With a BJT, this would be necessary since the base-emitter junction of a BJT basically looks like a diode to the circuit which drives it. R1 is not necessary with a FET but does have the effect of increasing the turn-on/off time of the FET due to the increased RC delay imposed by the 1kOhm resistor and the capacitance of the FET's base input. Of course, this additional RC delay has no effect on the relay since the time for the relay to open and close is so much longer, but it would be more significant if the MOSFET were driving other electronics, rather than a relay.