Due to the massive number of devices in the M2M communication era, new challenges have been brought to the existing random-access (RA) mechanism, such as severe preamble collisions and resource block (RB) wastes. To address these problems, a novel sparse message passing (SMP) algorithm is proposed, based on a factor graph on which Bernoulli messages are updated. The SMP enables an accurate estimation on the activity of the devices and the identity of the preamble chosen by each active device. Aided by the estimation, the RB efficiency for the uplink data transmission can be improved, especially among the collided devices. In addition, an analytical tool is derived to analyze the iterative evolution and convergence of the SMP algorithm. Finally, numerical simulations are provided to verify the validity of our analytical results and the significant improvement of the proposed SMP on estimation error rate even when preamble collision occurs.