Remember how Galdriel corrects Sam when he speaks of elvish magic. I don't think that either Tolkien or the elves would think of Sam's words as "magic", as in say these words and this will happen.
Sam is saying a prayer to Elbereth (Varda) one of the two most powerful guardians living on Arda (the world). The words are in What does Sam shout when he uses the Phial? (which is linked to this question), and the translation is given in Edlothian's answer to that question. As a Christian, Tolkien believes that prayers are powerful, but the power comes, not from the actual words, but from the intention and the faith behind them.
How does Sam know the words? They are similar to, but not the same as, the words he heard when he met Gildor in the Shire. It is possible that he heard this version of the prayer while staying at Rivendell. We are told that he is thinking of the elves of Rivendell singing to Elbereth immediately before he utters the prayer.
‘Galadriel!’ he said faintly, and then he heard voices far off but clear: the crying of the Elves as they walked under the stars in the beloved shadows of the Shire, and the music of the Elves as it came through his sleep in the Hall of Fire in the house of Elrond.
Gilthoniel A Elbereth!
The Lord of the Rings Book Four, Chapter 10: The Choices of Master Samwise
Page 729 (Houghton Mifflin Harcourt; Single Volume 50th Anniversary Edition)
What prompts Sam to say those words? I think we have to assume that his use of the words (and perhaps the words themselves) are inspired. So who inspired them? Tolkien often makes clear that something is meant to happen without explicitly saying who means it to happen. We may often feel that it must be Eru or one of the Valar, and I think we can do the same here. Not so much a case of Deus ex machina but more of Deus ex Deo.