Can I book Thai railway tickets online?
Yes, as of February 2017 the official State Railway of Thailand (SRT) online booking system is online again, after being suspended for about 4 years. Here you can book train tickets directly with the SRT and receive them as PDF's (that need to be printed prior to boarding the train).
Note that in my experience, actual arrival times of the sleeper trains are usually always at least an hour later than the scheduled arrival time, so keep that in mind when planning connecting transports etc.
Other ways to book train tickets:
Directly at a train station
Note that popular routes sell out, so booking ahead of time is recommended. It's possible to book up to 60 days ahead.
+66 222 337 62, +66 222 477 88 or +66 222 503 00
Via an agent
There are many, but one that seems to be often recommended if you want to book online and travel from Bangkok is 12Go Asia, since they have an office in conjunction to the Hua Lumpong train station in Bangkok. Note that booking via agents typically require that you pick up your tickets at the agent, which is the reason the above mentioned company is convenient (since you're going to the train station anyway, and can pick up your tickets at their office).