The rare win for Bangladesh -- just their fourth away from home and first against Sri Lanka in 18 attempts -- ended the two-Test series in a draw after the visitors endured a 259-run loss in the opener in Galle.
Chasing a target of 191, teenage batsman Mehedi Hasan hit the winning run after an anxious half hour in the final session on the fifth day, getting Bangladesh across the line in 57.5 overs.
Tamim laid the groundwork with his 22nd Test fifty, teaming up with Sabbir Rahman who made 41 runs and shared 109 for the third wicket with the left-hander.
Sri Lanka struck in phases through spinners Dilruwan Perera and skipper Rangana Herath, who grabbed three wickets each, but lacked the cutting edge to deny Bangladesh from celebrating their 100th Test match in style.
Bangladesh began looking nervous when Tamim -- who faced 82 balls and hit seven fours and a six -- hoisted a catch to Dinesh Chandimal off Perera just before the tea break.
Perera then removed Sabbir through a successful review after the bowler's initial appeal for a leg-before was rejected, giving Sri Lanka an outside chance for a win.
Mushifiqur Rahim and Shakib Al Hasan got Bangladesh through to the tea break with 35 runs still needed, but Herath got a lucky breakthrough soon after the resumption as Shakib dragged a ball to stumps on 15.
Mushfiqur remained unbeaten on 22 to take Bangladesh home with some support from debutant Mosaddek Hossain, who made 13 runs during the crucial period.
Herath claimed his first wicket when opener Soumya Sarkar, charging down the pitch, was deceived by a turn and lofted a catch to Upul Tharanga at mid-off for 10.
Imrul Kayes edged the next ball to slip fielder Asela Gunaratne for a duck.
Perera hit his fourth Test fifty off 174 balls while tail-ender Lakmal smashed 42 off 48 balls. The duo shared 80 runs for the ninth wicket before Bangladesh separated them through a run out.