Reputation:
Here is my code:
for msg in mbox:
try:
pprint.pprint(msg._headers, stream = f)
tempdate = parser.parse(msg['Date'])
newdate = str(tempdate)[:19]
ip = msg['x-originating-ip']
iplookup = (ip.strip("[]"))
url = 'http://freegeoip.net/json/{}'.format(iplookup)
response = urllib.request.urlopen(url).read()
result = json.loads(response.decode('utf8'))
f.write ('Country = ' + (result['country_name']) + '\n')
f.write ('Region = ' + (result['region_name']) + '\n')
f.write ('City = ' + (result['city']) + '\n')
However, not all emails have originiting IP. how can i check to see if the x orginiting ip is set? Something like an IF staement
ip = msg['x-originating-ip']
if (isset(ip):
iplookup = (ip.strip("[]"))
url = 'http://freegeoip.net/json/{}'.format(iplookup)
response = urllib.request.urlopen(url).read()
result = json.loads(response.decode('utf8'))
f.write ('Country = ' + (result['country_name']) + '\n')
f.write ('Region = ' + (result['region_name']) + '\n')
f.write ('City = ' + (result['city']) + '\n')
else:
continue
Thats an example i thought of, but the isset function is from php, not python? Any ideas?
Upvotes: 1
Views: 78
Reputation: 15537
Try
if 'x-originating-ip' in msg:
...
It uses the in
operator. It only checks if the key is set, not what the value is - so it can still be None
or False
or an empty string or list or something. You can also use 'foo' not in x
instead of not 'foo' in x
.
If you want to check that it's not None
at the same time, for example, use get()
instead:
if msg.get('x-originating-ip') is not None:
...
Upvotes: 1
Reputation: 21241
You can check value of x-originating-ip
is set or not using get.
ip = msg.get('x-originating-ip')
if ip:
...
....
Upvotes: 0