WASHINGTON — Kirstjen Nielsen, the homeland security secretary, recently warned dozens of foreign diplomats — including the Russian ambassador — that the United States would retaliate if adversaries abroad meddled in its coming elections.

“To those who would try to attack our democracy, to affect our elections, to affect the elections of other countries, to undermine national sovereignty, I have a word of warning: Don’t,” Ms. Nielsen told an estimated 80 foreign envoys and other officials during a speech last week, according to a person in attendance.

Two other people with knowledge of the event confirmed the comments. All three spoke on the condition of anonymity because the remarks were given at a closed-door meeting.

It was an unusually stern warning by Ms. Nielsen, and was among the harshest threats of retaliation by a member of President Trump’s cabinet. Ms. Nielsen is one of the most outspoken advocates of the administration’s policies, and has resisted being drawn into the controversy over Russian meddling during the 2016 election that put Mr. Trump in office.