Politicians in Mexico have largely remained silent on Mr. Trump, though there have been outbursts, including from Mr. Peña Nieto himself. In March, he compared Mr. Trump to Hitler and Mussolini for what he called Mr. Trump’s strident remarks and populism, though he later tried to soften his words without quite taking them back.

The trip will take place hours before Mr. Trump is to give a speech in Phoenix that is expected to clarify his stance on immigration, which has plagued his campaign over the past few weeks as he has wavered on key elements of his platform. His campaign has given conflicting signals over whether he will stick to the hard-line positions he took during the Republican primaries, particularly on deportations, and he suggested recently that he was open to “softening” some of his proposals. But his calls to have Mexico pay for the wall have continued.

“From the first days of his campaign, Donald Trump has painted Mexicans as ‘rapists’ and criminals and has promised to deport 16 million people, including children and U.S. citizens,” Jennifer Palmieri, the Clinton campaign’s communications director, said in a statement. “What ultimately matters is what Donald Trump says to voters in Arizona, not Mexico, and whether he remains committed to the splitting up of families and deportation of millions.”

The trip is the latest gamble for Mr. Trump and his struggling campaign. But for all the risk it poses, it offers an image Mr. Trump relishes: of a wily negotiator willing to do the unexpected — meeting with a perceived enemy — to advance his agenda.

It will also be his first official meeting with a head of state as the Republican presidential nominee.

Despite Mr. Trump’s routine scolding of Mexico and its leadership, several of his closest allies have warm ties with the country and its president. Gov. Chris Christie of New Jersey, a top Trump adviser and confidant, traveled to Mexico in 2014 to meet with Mr. Peña Nieto, arguing that it was imperative for the United States to put Mexico at the center of its foreign relations.