Skip to content

Instantly share code, notes, and snippets.

@agoldst
Last active November 28, 2023 01:15
Show Gist options
  • Save agoldst/2c538d9184f44373b76cfc798fd62c19 to your computer and use it in GitHub Desktop.
Save agoldst/2c538d9184f44373b76cfc798fd62c19 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
@rmpbklyn
Copy link

rmpbklyn commented Jan 3, 2022

wonderful was looking on how to make csv , thx for posting

@jamm1985
Copy link

Thank you!

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