Find Location & IP Address of Email Sender

If you would like to know the IP Address and Location of email sender in Gmail, Google Scripts can help. It extracts the raw headers of the email message and then pull the IP address of the sender using regular expressions.

The IP address is then passed to a free GeoIP service that gives the geographic location of an IP address. The JSON response may contain the country name, city and even the zip code in some cases.

Also see: Find Person by Email Address

function getEmailCountry(messageID) {
  var message = GmailApp.getMessageById(messageID);
  var raw = message.getRawContent().split('\\n');

  for (var j = 0; j < raw.length; j++) {
    var ipaddress = /Received:\\s+from.*?\[((?:[0-9]{1,3}\.){3}[0-9]{1,3})\]/i.exec(raw[j]);

    if (ipaddress != null) {
      var json,
        reply = { country_name: 'Unknown' };

      try {
        json = UrlFetchApp.fetch('' + ipaddress[1]);
        reply = JSON.parse(json);
      } catch (e) {}

      Logger.log('The email is sent from ' + ipaddress[1] + ' in ' + reply.country_name);
Amit Agarwal

Amit Agarwal

Google Developer Expert, Google Cloud Champion

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.

Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory


Awards & Titles

Digital Inspiration has won several awards since it's launch in 2004.

Google Developer Expert

Google Developer Expert

Google awarded us the Google Developer Expert award recogizing our work in Google Workspace.

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards in 2017.

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional (MVP) title for 5 years in a row.

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator title recognizing our technical skill and expertise.

Email Newsletter

Sign up for our email newsletter to stay up to date.

We will never send any spam emails. Promise.