According to the two former employees, Yahoo Chief Executive Marissa Mayer's decision to obey the directive roiled some senior executives and led to the June 2015 departure of Chief Information Security Officer Alex Stamos, who now holds the top security job at Facebook.
"Yahoo is a law abiding company, and complies with the laws of the United States," the company said in a brief statement in response to Reuters questions about the demand. Yahoo declined any further comment.
Through a Facebook spokesman, Stamos declined a request for an interview.
The NSA referred questions to the Office of the Director of National Intelligence, which declined to comment.
The demand to search Yahoo Mail accounts came in the form of a classified directive sent to the company's legal team, according to the three people familiar with the matter.
US phone and internet companies are known to have handed over bulk customer data to intelligence agencies. But some former government officials and private surveillance experts said they had not previously seen either such a broad directive for real-time Web collection or one that required the creation of a new computer program.
"I've never seen that, a wiretap in real time on a 'selector,'" said Albert Gidari, a lawyer who represented phone and internet companies on surveillance issues for 20 years before moving to Stanford University this year.
A selector refers to a type of search term used to zero in on specific information.
"It would be really difficult for a provider to do that," he added.
Yahoo is a law abiding company, and complies with the laws of the United States.
Reuters was unable to confirm whether the 2015 demand went to other companies, or if any complied.
Alphabet's Google and Microsoft, two major US email service providers, did not respond to requests for comment.
Under laws including the 2008 amendments to the Foreign Intelligence Surveillance Act, intelligence agencies can ask US phone and Internet companies to provide customer data to aid foreign intelligence-gathering efforts for a variety of reasons, including prevention of terrorist attacks.
Disclosures by former NSA contractor Edward Snowden and others have exposed the extent of electronic surveillance and led US authorities to modestly scale back some of the programs, in part to protect privacy rights.
Companies including Yahoo have challenged some classified surveillance before the Foreign Intelligence Surveillance Court, a secret tribunal.
As tech companies become better at encrypting data, they are likely to face more such requests from spy agencies.