We consider the problem of approximating the unknown density $u\in L^2(\Omega,\lambda)$ of a measure $\mu$ on $\Omega\subset\R^n$, absolutely continuous with respect to some given reference measure $\lambda$, from the only knowledge of finitely many moments of $\mu$. Given $d\in\N$ and moments of order $d$, we provide a polynomial $p_d$ which minimizes the mean square error $\int (u-p)^2d\lambda$ over all polynomials $p$ of degree at most $d$. If there is no additional requirement, $p_d$ is obtained as solution of a linear system. In addition, if $p_d$ is expressed in the basis of polynomials that are orthonormal with respect to $\lambda$, its vector of coefficients is just the vector of given moments and no computation is needed. Moreover $p_d\to u$ in $L^2(\Omega,\lambda)$ as $d\to\infty$. In general nonnegativity of $p_d$ is not guaranteed even though $u$ is nonnegative. However, with this additional nonnegativity requirement one obtains analogous results but computing $p_d\geq0$ that minimizes $\int (u-p)^2d\lambda$ now requires solving an appropriate semidefinite program. We have tested the approach on some applications arising from the reconstruction of geometrical objects and the approximation of solutions of nonlinear differential equations. In all cases our results are significantly better than those obtained with the maximum entropy technique for estimating $u$.