If you are in a cheerful mood it is easier to get people to share your interests and feelings than if you are solemn or sad, when people tend to keep away from you.
Though the general idea of the proverb was current long before that, it was given its present form in 1883 by Ella Wheeler Wilcox. It comes in her poem called Solitude:
Laugh and the world laughs with you,
Weep and you weep alone,
For the sad old earth must borrow its mirth,
But has trouble enough of its own.