This is a corollary of Whitney's extension theorem: see Theorem 1 in the link below.
http://www.ams.org/journals/tran/1934-036-01/S0002-9947-1934-1501735-3/S0002-9947-1934-1501735-3.pdf
According to the theorem we can find a smooth function $F$ where $F|_M = f$. Now we would like to have $F|_{U^c} = 0$. Assume we have a smooth function $\phi$ , which has value 1 on $M$ and 0 on $U^c$. Then we can define $\bar{f} = \phi F$ .
So, we need to construct $\phi$: If M is compact, the result is known as $C^\infty$ Urysohn lemma: see, e.g here. For non-compact, i.e unbounded closed set $M$ we reduce the problem to the case where $M$ is bounded (hence compact). Find a ball $B \in U \cap M^c$ . WLOG $B = B_1(0)$ Perform the Kelvin transform $$T(x) = \frac{x}{||x||_2^2}$$. This is a smooth homeomorphism $\mathbb{R}^n - 0 \to \mathbb{R}^n - 0$, which sends $M$ to a closed subset of the unit ball and $U$ is mapped to an open subset of $\mathbb{R}^n$. Also, $\mathbb{R}^n - B_1(0) \in U$, so we are in the case where $M$ is compact. Find $\phi$ using the $C^\infty$ Urysohn lemma. Then $\phi (T^{-1}(x))$ is $1$ on M and $0$ on $U^c$ which we wanted to find.