Take the 2-minute tour ×

Hello I am looking to write an independent script to log into an e-mail account [IMAP], get the headers for each e-mail, locate & store the (sender's or server's) IP address from each one. I recognize that this has to be a bit comprehensive to cover the top 3 webmail providers (Yahoo, Google & Hotmail) as well as the other common header formats.

Ideally, I would like to get the senders' IP addresses, but would settle for the servers' IP addresses.

I need to do this in PHP in a regular LAMP setup.

Any ideas would help. Thank you.

share|improve this question
What exactly do you mean by "IP address from each one"? Doing that is a task in itself (and many mail services don't include the dynamic IP of the originating machine any more) –  Pekka 웃 Dec 24 '10 at 22:14
I would like to locate & store the IP address from the header of each e-mail received in the IMAP mailbox. –  Abhic Dec 24 '10 at 22:17
You are repeating yourself, but it is still not clear what you are wanting to do here. IP addresses are allocated to computers/servers on a network. Are you wanting to "locate & store" the addresses for the IP Address of a server the message comes from, a server the message comes through (there can be more than one) or the computer the sender used to create the email? –  Lucanos Dec 25 '10 at 1:53
@Lucanos I get it now, I would like to get the senders' IP addresses, but would settle for servers' IP addresses. –  Abhic Dec 25 '10 at 16:57

4 Answers 4

up vote 3 down vote accepted

The details of the servers the system transits through are shown in the top of the email header in reverse-chronological order - the most recent are at the top, the first servers are at the bottom.

A quick, off-the-cuff solution would be to use a RegExp to try and find the bottom "Received:..." line containing an IP address.

A very quick test suggests that:

$regExp = '/Received:.*((?:\d+\.){3}\d+)/';

will match the lines, and return IP addresses.

Then you'd just use something like preg_match_all() to return an array of matched lines, and use the last one of the lot.

share|improve this answer

That IP is IP of server who mailed it, not the sender IP. Do you want servers IP or senders IP?

share|improve this answer
Ah now I get it. I would like to get the senders' IP addresses, but would settle for servers' IP addresses. –  Abhic Dec 25 '10 at 16:56
@Abhic: In many cases the senders' IP addresses will be useless to you as a lot of PCs are on private networks. See en.wikipedia.org/wiki/Private_network –  Brian Rasmussen Feb 10 '11 at 18:44

After you connected, got the messages list and now is foreaching a message:


It works like a breeze for me.

share|improve this answer

I know this post is old but the above selected answer does get an IP but it does not necessarily get the correct sending server IP address. Below is the regex I used to get the actual sending servers IP:

share|improve this answer

Your Answer


