I had accepted an offer letter from an employer 45 days ago, but now I got another (better) offer letter from a different company. Now I am wondering, what should I write in a letter to HR at the first company in order to inform them that I will not be joining them after all? I was supposed to start in 15 days.
Declining an offer after already accepting it is very unprofessional (at least) and maybe illegal (breaking some terms of contract), it can also severely burn bridges for you. Moreover, in your case, you took 3/4th of the time to revise your decision - which makes it even worse.
Read the offer letter acceptance criterion carefully and if you're ready for the facing the consequences (if any) of backing out, send an email mentioning:
"Hello, I regretfully inform you that due to the circumstances, I will not be able to join your organization. It was a pleasure having the chance to be part of the organization. Thanks."
Keep it short and simple.
Make it very short and simple.
There is nothing you can say that will change what you have done.
Let them know now, so they can get started on either contacting another finalist, or starting the search over.
Now keep in mind depending on what you signed, and what country you are in you could be in violation of a contract with penalties.
You have no obligation to write an apology letter, and in my personal opinion, it would be pretty tacky to do so. If you haven't signed anything with the first company, you didn't commit to them yet and it isn't too late to change your mind. They will (or, at least, should) understand this. Simply tell them that you've changed your mind about the offer and move on.