Skip to content

Instantly share code, notes, and snippets.

@dhondta
Last active August 28, 2023 03:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dhondta/9a8027062ff770b2aa5d8422ddd78b57 to your computer and use it in GitHub Desktop.
Save dhondta/9a8027062ff770b2aa5d8422ddd78b57 to your computer and use it in GitHub Desktop.
Tinyscript tool for getting IP locations from an email (EML file)

Get Email Origin

This Tinyscript-based allows to load an email and to parse the receivers, indicating where the found IP addesses originate from.

This can be installed using:

$ pip install ipaddress mail_parser maxminddb-geolite2 tinyscript
$ tsm install get-email-origin
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import ipaddress
import mailparser
from geolite2 import geolite2
from tinyscript import *
__author__ = "Alexandre D'Hondt"
__version__ = "1.2"
__copyright__ = "A. D'Hondt"
__license__ = "agpl-3.0"
__doc__ = """
This tool loads an email and parses the receivers, indicating where the found IP addesses originate from.
"""
__examples__ = ["message.eml"]
IP_REGEX = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
MMDDB = geolite2.reader()
def parse_eml(eml):
ips = []
found = False
logger.debug("Parsing receivers...")
for receiver in eml.received:
for addr in IP_REGEX.findall(receiver.get('raw', "")):
addr = ipaddress.ip_address(addr)
if str(addr) in ips:
continue
ips.append(str(addr))
logger.debug("Found: {}{}".format(addr, ["", " (private)"][addr.is_private]))
if not addr.is_private:
s, found = str(addr), True
d = MMDDB.get(s)
for f in ["city", "country", "continent"]:
i = d.get(f, {}).get('names', {}).get('en')
if i:
s += "\n{: <9}: {}".format(f.capitalize(), i)
l = d.get('location')
if l:
s += "\nLocation : Lat {} Lon {}".format(l['latitude'], l['longitude'])
try:
s += " ({})".format(l['time_zone'])
except:
pass
logger.info(s)
def valid_eml(filename):
try:
with open(filename) as f:
eml = mailparser.parse_from_file_obj(f)
return eml
except:
raise argparse.ArgumentTypeError
if __name__ == '__main__':
parser.add_argument("eml", type=valid_eml, help="email file")
initialize()
parse_eml(args.eml)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment