Skip to content

Instantly share code, notes, and snippets.

@nvk
Forked from agoldst/contacts_query.sh
Created September 12, 2022 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nvk/70e375007ca64f6d7644d23920b74f89 to your computer and use it in GitHub Desktop.
Save nvk/70e375007ca64f6d7644d23920b74f89 to your computer and use it in GitHub Desktop.
Query macOS contacts for mutt
#!/bin/bash
#
# contacts_query.sh
# Andrew Goldstone, July 2017. All yours to use or modify, but no promises.
#
# The mutt e-mail client has an option to query an external address book for
# e-mail addresses. On a Mac it is nice to be able to query the Address Book
# (now known as Contacts). For a while I used a utility called contacts
# (http://gnufoo.org/contacts) but this stopped working under Sierra. There is
# an official API for querying Contacts as a unified datastore, but it is only
# accessible via Swift and Objective-C, so that's a project for another day.
# However, I learned from the internet that address book contacts are stored in
# a sqlite database, or rather, it turns out, databases, one for each "source"
# (On My Mac, Google Contacts, etc.). Provided you have sqlite installed on
# your system, you can produce suitable query results for mutt with something
# like the below.
#
# In your muttrc, do
#
# set query_command="/path/to/contacts_query.sh '%s'"
#
# This version does matches with any part of the first name, last name, or
# e-mail.
set -e
IFS="$(printf '\n')" # Application<space>Support is the devil
addr_root="$HOME/Library/Application Support/AddressBook"
main_db="$addr_root/AddressBook-v22.abcddb"
other_dbs=$addr_root/Sources/*/AddressBook-v22.abcddb
cmd="
select ZABCDEMAILADDRESS.ZADDRESS,
(ZABCDRECORD.ZFIRSTNAME || ' ' || ZABCDRECORD.ZLASTNAME)
from ZABCDRECORD
inner join ZABCDEMAILADDRESS
on ZABCDRECORD.Z_PK = ZABCDEMAILADDRESS.ZOWNER
where
ZABCDRECORD.ZFIRSTNAME like \"%$1%\"
or ZABCDRECORD.ZLASTNAME like \"%$1%\"
or ZABCDEMAILADDRESS.ZADDRESS like \"%$1%\";
"
results=()
for db in $main_db $other_dbs; do
results+=($(sqlite3 "$db" "$cmd" -separator $'\t'))
done
if [ -z "$results" ]; then
echo "No results found"
exit 1
else
echo "Address Book results:"
printf '%s\n' "${results[@]}" | sort -k 2 | uniq
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment