Skip to content

Instantly share code, notes, and snippets.

@cleverdevil
Last active May 31, 2022 12:03
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cleverdevil/a536bfa68b066c6fd593 to your computer and use it in GitHub Desktop.
Save cleverdevil/a536bfa68b066c6fd593 to your computer and use it in GitHub Desktop.
Integrate Mac OS X Contacts database with mutt for auto-completion of email addresses
#!/usr/bin/env python
'''
A script to search the Mac OS X Address Book via PyObjC bridge, and
then output the results in a format suitable for integration with
mutt.
Add the following to your `.muttrc`:
set query_command = "~/.mutt/contacts.py '%s'"
bind editor <Tab> complete-query
bind editor ^T complete
Then, tab-complete emails like a boss.
'''
import sys
import AddressBook as AB
# get a reference to the address book
book = AB.ABAddressBook.sharedAddressBook()
# create search parameters - prefix match on first or last name or email
firstname_search = AB.ABPersonCreateSearchElement(
AB.kABLastNameProperty, None, None, sys.argv[1],
AB.kABPrefixMatchCaseInsensitive
)
lastname_search = AB.ABPersonCreateSearchElement(
AB.kABFirstNameProperty, None, None, sys.argv[1],
AB.kABPrefixMatchCaseInsensitive
)
email_search = AB.ABPersonCreateSearchElement(
AB.kABEmailProperty, None, None, sys.argv[1],
AB.kABContainsSubStringCaseInsensitive
)
name_search = AB.ABSearchElement.searchElementForConjunction_children_(
AB.kABSearchOr,
[firstname_search, lastname_search, email_search]
)
# perform the search
matches = book.recordsMatchingSearchElement_(name_search)
# collect results
results = []
for person in matches:
emails = person.valueForKey_('Email') or []
company = person.valueForKey_('Organization')
name = '%s %s' % (
person.valueForKey_('First'),
person.valueForKey_('Last')
) if person.valueForKey_('First') else company
for i in range(len(emails)):
results.append((
emails.valueAtIndex_(i),
name
))
# sort results
results.sort(lambda x,y: cmp(x[1], y[1]))
# output to stdout in the mutt-preferred style
print 'EMAIL\tNAME'
for result in results:
print '%s\t%s' % result
@tanrax
Copy link

tanrax commented Jul 4, 2016

import AddressBook as AB
ImportError: No module named AddressBook

@tristancollins
Copy link

Running this code gives me an error:

./contacts.py 'Tristan'
Traceback (most recent call last):
  File "./contacts.py", line 54, in <module>
    for i in range(len(emails)):
TypeError: object of type 'ABMultiValueCoreDataWrapper' has no len()

This is with the latest python AddressBook module.

Any ideas?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment