“We are in the middle of a jobs crisis, a border crisis, and a terrorism crisis,” he said. “This election is our last chance to secure the border, stop illegal immigration, and reform our laws to make your life better. This is it. We won’t get another opportunity – it will be too late.”

The whirlwind day started after Mr. Trump accepted an invitation from Mr. Peña Nieto to meet him at the presidential palace to discuss economic and border concerns. For the most part they managed to sidestep combustible issues and ignore raging hostility from average Mexicans. Mr. Trump has called them rapists and drug dealers, and he did not apologize for those remarks during a joint news conference when a reporter pressed him for any regrets.

Instead, as an impassive Mr. Peña Nieto looked on, Mr. Trump sounded conciliatory themes about working together to improve border security. Gone, at least for this foreign trip, were the threats about American interests and superiority that have defined Mr. Trump’s candidacy and electrified his supporters.

“I think it was an excellent meeting,” Mr. Trump said.

Mr. Peña Nieto, who pointedly emphasized goals like “mutual respect” and “constructive” relations several times in his remarks, did Mr. Trump some favors with his respectful treatment: The Mexican president acknowledged that every country had a “right” to protect its own border, and suggested that Mr. Trump wanted to move on from his antagonistic remarks of the past.

“The Mexican people felt aggrieved by those comments,” Mr. Peña Nieto said. “But I am certain that he has a genuine interest in building a relationship that would lead us to provide better conditions to our people.”

Mr. Trump’s unexpected trip to Mexico was timed to steer attention from his significant shifts on immigration policy. He flew to Mexico just hours before he was scheduled to deliver a major speech on immigration after more than a week of mixed signals about his immigration views, which he said were “softening” and then “hardening” in the space of two days last week.

On a more personal level, Mr. Trump also wanted to show undecided voters that he had the temperament and self-control of a statesman — qualities that many doubt he has — and also demonstrate that Americans did not need to worry every time he opened his mouth in a foreign country. He also hoped to show that he could acquit himself well on the world stage, something that is a clear strength of Mrs. Clinton, a former secretary of state, senator and first lady.