Extract and convert vcf contacts from emails in python
I wasn’t able to export my contacts from my iphone (iOS 11). Thus I mailed each
contact to myself using an alias e.g. john.doe+contact@example.com
. I’m using
mu (mail indexer/searcher) version 1.6.4
for my emails. Everything else happens below:
Extract vcf file from email
contacts=~/tmp/iPhoneContacts
rm -r $contacts
mkdir $contacts
cd $contacts
foundEmails=$(mu find to:$myemail --fields "l")
for email in $foundEmails
do
mu extract $email '.*.vcf'
done
Export vcf to tsv file
import fnmatch
import os
import re
import phonenumbers
ROOTPATH = '/home/ra/tmp/iPhoneContacts/'
PATTERN = '*.vcf'
TSV = open('/home/ra/tmp/iPhoneContacts/iPhoneContacts.tsv', 'w')
def contacts():
l = set()
for root, dirs, files in os.walk(ROOTPATH):
for filename in fnmatch.filter(files, PATTERN):
l.add(os.path.join(root, filename))
return (l)
contactsList = contacts()
print("Total %s files:" % (PATTERN), len(contactsList))
for contactFile in contactsList:
with open(contactFile, "r") as f:
#Gets Peter Mueller Meier.contact from /home/ra/tmp/iPhoneContacts/Peter Mueller Meier.contact
contactName = contactFile[(contactFile.rfind('/')) + 1::]
#Gets Peter Mueller Meier from Peter Mueller Meier.contact
contactName = contactName.split(".")[0]
#Gets remaining words after space e.g. Mueller Meier from Peter Mueller Meier
contactName = contactName.split(" ")
#Gets Peter from Peter Mueller Meier
contactFirstName = contactName[0]
#Gets Mueller Meier from Peter Mueller Meier
contactLastName = " ".join(
contactName[1:]) if (len(contactName)) > 1 else ""
numbrs = [
phonenumbers.format_number(match.number,
phonenumbers.PhoneNumberFormat.E164)
for match in phonenumbers.PhoneNumberMatcher(f.read(), "CH")
]
print(contactFirstName,
contactLastName,
"\t".join(numbrs),
sep="\t",
file=TSV)
TSV.close()