From Handbook of Every Day Islam by Imam Hassan Qazwini
A lottery is deemed by many Muslim scholars to be a form of gambling, and Islam is known to prohibit gambling. However, if an individual buys a lottery ticket intending to help a charitable cause (a school or hospital fund-raiser, for example) rather than to win a prize, then this is a form of donation, not gambling. Buying a lottery ticket to win a prize is a form of gambling and is entirely prohibited.
Note that accepting a prize, should one win, is not an issue. Muslims can lawfully accept a prize regardless of their motivation. As far as winning the prize, both groups – those who bought the lottery with the intention of gambling and those who bought the ticket with the intention of donating to a charitable cause – can accept the prize lawfully should they win. The reason for this is because the law of the land considers giving this prize legitimate, and therefore accepting the prize is not problematic, just like receiving interest from non-Muslim banks is legitimate as the law of the land allows it.
In conclusion, buying lottery tickets itself is prohibited if it is done with the intention of winning the lottery. If not, then it is not prohibited. In both cases, obtaining the prize is not prohibited, and taking the prize is legitimate.
It is worth mentioning that some people buy lottery tickets with the intention of winning the prize and using it for charitable causes such as building mosques or Islamic schools. These good intentions, however, do not legitimize the buying of a lottery ticket. Since the intent of purchasing a ticket is to win a prize, then it is considered gambling in Islam.