His mother was Nakşidil Valide Sultan. In 1808, Mahmud II's predecessor, and half-brother, Mustafa IV ordered his execution along with his cousin, the deposed Sultan Selim III, in order to defuse the rebellion. Selim III was killed, but Mahmud was safely kept hidden by his mother and was placed on the throne after the rebels deposed Mustafa IV. The leader of this rebellion, Alemdar Mustafa Pasha, later became Mahmud II's vizier. Western historians give Mahmud a poor reputation for simply being the Sultan during a time of deterioration of the Ottoman Empire.
There are many stories surrounding the circumstances of his attempted murder. A version by the 19th-century Ottoman historian Ahmed Cevdet Pasha gives the following account: one of his slaves, a Georgian girl named Cevri, gathered ashes when she heard the commotion in the palace surrounding the murder of Selim III. When the assassins approached the harem chambers where Mahmud was staying, she was able to keep them away for a while by throwing ashes into their faces, temporarily blinding them. This allowed Mahmud to escape through a window and climb onto the roof of the harem. He apparently ran to the roof of the Third Court where other pages saw him and helped him come down with pieces of clothes that were quickly tied together as a ladder. By this time one of the leaders of the rebellion, Alemdar Mustafa Pasha arrived with his armed men, and upon seeing the dead body of Selim III proclaimed Mahmud as padishah. The slave girl Cevri Kalfa was awarded for her bravery and loyalty and appointed haznedar usta, the chief treasurer of the Imperial Harem, which was the second most important position in the hierarchy. A plain stone staircase at the Altınyol (Golden Way) of the Harem is called Staircase of Cevri (Jevri) Kalfa, since the events apparently happened around there and are associated with her.