This question already has an answer here:
- Why are there so many medicinal plants? 2 answers
There are many types of plants which produce chemicals which can be beneficial in treating human illnesses, or at least alleviate painful symptoms.
Why would they do that?
Is it just random chance, like some plants being poisonous, some having no effect, and some having beneficial effects? However, for poison there are evolutionary benefits, as it might reduce the chance of animals eating the plant.
Many plant species produce tasty fruits for the purpose of having animals eat them and disperse the seeds. However, for most plants used for medicinal purposes, the leaves, roots or flowers are used, the cultivation of which doesn't seem to be useful for the plant itself.