Επειδή μου χρειάστηκε να βγάλω κάτι contacts από ένα mail server για να τα βάλω σε μια mailing (news) list, έφτιαξα το παρακάτω #python script που μετατρέπει vcf σε csv. Το vcf μου το έφτιαξε το #roundcube που είναι web UI για τον mail server, με export των contacts και το csv έγινε import σε #listmonk. Το script τσεκάρει αν υπάρχει καταχωρημένο email αλλιώς απορρίπτει την επαφή.
Εκτελείται απλά με python vcf_to_csv.py contacts.vcf, χρησιμοποιείστε και μετατρέψτε ελεύθερα.
import vobject
import csv
import sys
# Check for input file argument
if len(sys.argv) < 2:
print("Usage: python vcf_to_csv.py <input_file.vcf>")
sys.exit(1)
input_vcf_file = sys.argv[1]
# Using a new, descriptive output file name
output_csv_file = input_vcf_file.replace('.vcf', '_email_only_filtered.csv')
def extract_name_email_attrs(vcf_path, csv_path):
data = []
# Define the required CSV header
data.append(['email', 'name', 'attributes'])
try:
with open(vcf_path, 'r', encoding='utf-8') as vcf_file:
# Read all vCards from the file
vCards = vobject.readComponents(vcf_file.read())
contacts_processed = 0
contacts_exported = 0
for card in vCards:
contacts_processed += 1
name = ''
email = ''
attributes = '' # Remains blank
# 1. Extract Full Name (FN)
if hasattr(card, 'fn'):
name = card.fn.value
# 2. Extract Email (only the first one found)
if hasattr(card, 'email') and card.email:
email = card.email_list[0].value
# 🌟 THE FILTER: Only append the contact if the email field is NOT empty
if email:
data.append([email, name, attributes])
contacts_exported += 1
# Note: If you also want to ensure a name exists, you could use:
# if email and name:
except FileNotFoundError:
print(f"Error: The file '{vcf_path}' was not found.")
return
except Exception as e:
print(f"An error occurred: {e}")
return
# Write the extracted data to the CSV file
try:
with open(csv_path, 'w', newline='', encoding='utf-8') as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerows(data)
print(f"✅ Conversion successful!")
print(f" Input file: {vcf_path}")
print(f" Output file: {csv_path}")
print(f" Contacts processed: {contacts_processed}")
print(f" Contacts with email exported: {contacts_exported}")
except Exception as e:
print(f"Error writing CSV file: {e}")
# Run the function
extract_name_email_attrs(input_vcf_file, output_csv_file)
