when and how can I write a thank you letter for my professor?
The text you are writing here is perfect! It is personal, highlights the relevant aspects, and it is not overly enthusiastic.

I personally would send it after the exam was taken and graded.