While delivering a sermon, Allah's Messenger (ﷺ) said, "If anyone of you comes while the Imam is delivering the sermon or has come out for it, he should offer a two rak`at prayer."
Sahih al-Bukhari Book 19, Hadith 49