Get any GitHub user’s email (Python)

Here’s a silly little Python script (github_email.py) I wrote to get a GitHub user’s email address based on their public event history.

It’s not bulletproof, but generally works:

from __future__ import print_function

import requests
import sys

from optparse import OptionParser


parser = OptionParser()
parser.add_option('-u', '--username', action='store', type='string', dest='username')
(options, args) = parser.parse_args()

gh_api_url = 'https://api.github.com/users/{username}/events/public'.format(username=options.username)

r = requests.get(gh_api_url)
r.raise_for_status()

gh_public_events = r.json()

if isinstance(gh_public_events, dict):
    if gh_public_events.get('message') and gh_public_events.get('message') == 'Not Found':
        print('User was not found!')
        sys.exit(0)

fullname = 'N/A'
email = 'N/A'

for event in gh_public_events:
    if event.get('payload').get('commits'):
        commits = event.get('payload').get('commits')
        for commit in commits:
            if commit.get('author'):
                fullname = commit.get('author').get('name')
                email = commit.get('author').get('email')
                break

print('Full Name: {name}'.format(name=fullname))
print('email: {email}'.format(email=email))

You can simply save this script as github_email.py (for example).

Also, do note, it uses Python 3, a deprecated standard library (optparse has been replaced by argparse) and one third party library, requests.

Usage Output

Usage: github_email.py [options]

Options:
  -h, --help            show this help message and exit
  -u USERNAME, --username=USERNAME

Expected Results

If the user exists and has public events:

$ github_email.py -u jbarnette
Full Name: John Barnette
email: jbarnette@github.com

If the user exists, but has no public events, you’ll get:

$ github_email.py -u test
Full Name: N/A
email: N/A

If the user does not exist, you’ll get:

$ github_email.py -u iou18y23123
User was not found!

And that’s how you get (almost) any GitHub user’s email!
It’s useful if you want to reach out to another contributor via email.

Disclaimer

The script is inspired from this blog post: How to Find Almost Any GitHub User’s Email Address

If you rather do this process manually, follow the instructions in the link right above.

github-email-blog