On November 12, 1966, Buzz Aldrin was on the Gemini 12 mission—a precursor to the Apollo missions—and he perched a camera that he had onboard the craft on the edge of a hatch, lifted his helmet's sun visor, and captured the first selfie in space, with the Earth sitting right behind him. 

Buzz Aldrin, first selfie in space, Gemini 12 (Credit: NASA/Buzz Aldrin)
(Image credit NASA/Buzz Aldrin)

In a Twitter exchange, Aldrin referred to it as "one expensive selfie stick!"

Aldrin had to open the pilot's hatch in order to capture the image. 

“So we had the camera and we couldn’t shoot this through the window. It had to be mounted on the spacecraft, firm, so it wouldn’t be shaking. And Jim Lovell would carefully point in the right direction, shut off the thrusters so that they wouldn’t flash during the time of exposure.

“I took a few pictures of things as we went over. And then I thought, I wonder if this could take a picture of me with the ultraviolet film. So I turned around, clicked the camera and it turned out pretty good!”

Here's how it came about: 

Aldrin and Neil Armstrong became the first two people to walk on the moon three years later. 

Also, the first Mars selfie was captured by Curiosity rover in 2014, but the one below is actually a composite of images so that more of the terrain could be included. However, the image of itself is genuine, taken with an extended robotic arm.

The marks you see below Curiosity are from the rover scuffing into the sand and scooping up samples from the dune it's on. 

NASA/JPL-CALTECH/MSSS Image credit NASA/JPL-CALTECH/MSSS