def get_company_by_email(domains_index, email):
    """Get company based on email domain

    Automatically maps email domain into company name. Prefers
    subdomains to root domains.

    :param domains_index: dict {domain -> company name}
    :param email: valid email. may be empty
    :return: company name or None if nothing matches
    """
    if not email:
        return None

    name, at, domain = email.partition('@')
    if domain:
        parts = domain.split('.')
        for i in range(len(parts), 1, -1):
            m = '.'.join(parts[len(parts) - i:])
            if m in domains_index:
                return domains_index[m]
    return None