Spaces:
Paused
Paused
File size: 13,602 Bytes
34367da | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 | #!/usr/bin/env python3
"""
📧 TDC Exchange/Outlook Harvester
Søger i emails efter SharePoint links, vedhæftninger og intern data
"""
import win32com.client
import pythoncom
import hashlib
import json
import re
from pathlib import Path
from datetime import datetime, timedelta
from neo4j import GraphDatabase
class TDCOutlookHarvester:
"""Harvester for TDC Outlook/Exchange data"""
NEO4J_URI = "neo4j+s://054eff27.databases.neo4j.io"
NEO4J_USER = "neo4j"
NEO4J_PASSWORD = "Qrt37mkb0xBZ7_ts5tG1J70K2mVDGPMF2L7Njlm7cg8"
# Søgetermer for relevante emails
SEARCH_TERMS = [
"strategi",
"roadmap",
"cybersikkerhed",
"cyber",
"SOC",
"NIS2",
"cloud",
"Azure",
"AI",
"kunstig intelligens",
"GPT",
"Copilot",
"Columbus",
"ERP",
"budget",
"forecast",
"finanstal",
"kunde",
"kontrakt",
"rammeaftale",
"SKI",
"produkt",
"CloudKey",
"prisliste"
]
def __init__(self):
self.output_dir = Path("data/outlook_harvest")
self.output_dir.mkdir(parents=True, exist_ok=True)
# Initialize COM for Outlook
pythoncom.CoInitialize()
print("📧 Connecting to Outlook...")
self.outlook = win32com.client.Dispatch("Outlook.Application")
self.namespace = self.outlook.GetNamespace("MAPI")
# Neo4j
self.neo4j = GraphDatabase.driver(
self.NEO4J_URI,
auth=(self.NEO4J_USER, self.NEO4J_PASSWORD)
)
self.emails = []
self.sharepoint_links = []
self.attachments = []
self.stats = {
"emails_scanned": 0,
"relevant_emails": 0,
"sharepoint_links": 0,
"attachments": 0
}
def get_folders(self):
"""List alle Outlook folders"""
folders = []
for account in self.namespace.Folders:
# Skip offentlige mapper
if "offentlig" in account.Name.lower() or "public" in account.Name.lower():
print(f"\n📁 Account: {account.Name} (skipped)")
continue
print(f"\n📁 Account: {account.Name}")
try:
for folder in account.Folders:
try:
folders.append({
"account": account.Name,
"folder": folder.Name,
"count": folder.Items.Count if hasattr(folder.Items, 'Count') else 0
})
print(f" └─ {folder.Name}: {folder.Items.Count if hasattr(folder.Items, 'Count') else '?'} items")
except:
continue
except Exception as e:
print(f" ⚠️ Could not access folders: {e}")
return folders
def search_folder(self, folder, search_term: str, max_items: int = 100) -> list:
"""Søg i en specifik folder"""
results = []
try:
# Outlook filter
filter_str = f"@SQL=\"urn:schemas:httpmail:subject\" LIKE '%{search_term}%' OR \"urn:schemas:httpmail:textdescription\" LIKE '%{search_term}%'"
items = folder.Items
items.Sort("[ReceivedTime]", True) # Nyeste først
count = 0
for item in items:
if count >= max_items:
break
try:
subject = getattr(item, 'Subject', '') or ''
body = getattr(item, 'Body', '') or ''
# Check if search term matches
if search_term.lower() in subject.lower() or search_term.lower() in body.lower():
# Extract SharePoint links
sp_links = re.findall(r'https://[a-zA-Z0-9.-]*sharepoint\.com[^\s<>"]*', body)
email_data = {
"subject": subject[:200],
"sender": str(getattr(item, 'SenderEmailAddress', '')),
"sender_name": str(getattr(item, 'SenderName', '')),
"received": str(getattr(item, 'ReceivedTime', '')),
"search_term": search_term,
"has_attachments": getattr(item, 'Attachments', None) and item.Attachments.Count > 0,
"attachment_count": item.Attachments.Count if hasattr(item, 'Attachments') else 0,
"sharepoint_links": sp_links[:10],
"body_preview": body[:500].replace('\r\n', ' ').replace('\n', ' ')
}
# Get attachment names
if email_data["has_attachments"]:
email_data["attachment_names"] = [
att.FileName for att in item.Attachments
][:10]
results.append(email_data)
self.sharepoint_links.extend(sp_links)
count += 1
except Exception as e:
continue
except Exception as e:
print(f" ⚠️ Search error: {e}")
return results
def harvest_inbox(self, days_back: int = 90, max_per_term: int = 50):
"""Harvest emails from inbox"""
print(f"\n📥 HARVESTING INBOX (last {days_back} days)")
print("-" * 50)
# Find TDC inbox
inbox = None
for account in self.namespace.Folders:
if "tdc" in account.Name.lower():
try:
inbox = account.Folders["Inbox"]
print(f" Found: {account.Name}/Inbox")
break
except:
# Try Indbakke (Danish)
try:
inbox = account.Folders["Indbakke"]
print(f" Found: {account.Name}/Indbakke")
break
except:
continue
if not inbox:
# Fallback to default inbox
inbox = self.namespace.GetDefaultFolder(6) # 6 = Inbox
print(f" Using default inbox")
print(f" Items in inbox: {inbox.Items.Count}")
# Search for each term
all_results = []
for term in self.SEARCH_TERMS:
print(f"\n 🔍 Searching: '{term}'")
results = self.search_folder(inbox, term, max_per_term)
for email in results:
# Avoid duplicates
if not any(e['subject'] == email['subject'] and e['received'] == email['received']
for e in all_results):
all_results.append(email)
self.save_to_neo4j(email)
self.stats["emails_scanned"] += max_per_term
self.stats["relevant_emails"] += len(results)
print(f" Found: {len(results)} relevant emails")
self.emails = all_results
return all_results
def harvest_sent_items(self, max_per_term: int = 30):
"""Harvest sent emails"""
print(f"\n📤 HARVESTING SENT ITEMS")
print("-" * 50)
sent = None
for account in self.namespace.Folders:
if "tdc" in account.Name.lower():
try:
sent = account.Folders["Sent Items"]
break
except:
try:
sent = account.Folders["Sendt post"]
break
except:
continue
if not sent:
sent = self.namespace.GetDefaultFolder(5) # 5 = Sent
results = []
for term in self.SEARCH_TERMS[:10]: # Færre terms for sent
found = self.search_folder(sent, term, max_per_term)
results.extend(found)
print(f" Found: {len(results)} relevant sent emails")
return results
def extract_sharepoint_links(self):
"""Udtræk alle unikke SharePoint links"""
unique_links = list(set(self.sharepoint_links))
self.stats["sharepoint_links"] = len(unique_links)
print(f"\n🔗 SHAREPOINT LINKS FOUND: {len(unique_links)}")
print("-" * 50)
for link in unique_links[:20]:
print(f" {link[:80]}...")
# Save to Neo4j
self.save_sharepoint_link(link)
return unique_links
def save_to_neo4j(self, email: dict):
"""Gem email i Neo4j"""
content_hash = hashlib.md5(
f"{email['subject']}:{email['received']}".encode()
).hexdigest()
with self.neo4j.session() as session:
session.run("""
MERGE (e:TDCEmail {contentHash: $hash})
ON CREATE SET
e.subject = $subject,
e.sender = $sender,
e.senderName = $sender_name,
e.received = $received,
e.searchTerm = $search_term,
e.hasAttachments = $has_attachments,
e.attachmentCount = $attachment_count,
e.bodyPreview = $body_preview,
e.harvestedAt = datetime()
MERGE (ds:DataSource {name: 'TDC_Exchange'})
ON CREATE SET ds.type = 'email'
MERGE (e)-[:HARVESTED_FROM]->(ds)
""",
hash=content_hash,
subject=email.get('subject', ''),
sender=email.get('sender', ''),
sender_name=email.get('sender_name', ''),
received=email.get('received', ''),
search_term=email.get('search_term', ''),
has_attachments=email.get('has_attachments', False),
attachment_count=email.get('attachment_count', 0),
body_preview=email.get('body_preview', '')[:1000]
)
# Link SharePoint URLs
for sp_link in email.get('sharepoint_links', []):
link_hash = hashlib.md5(sp_link.encode()).hexdigest()
session.run("""
MERGE (sp:SharePointLink {contentHash: $hash})
ON CREATE SET sp.url = $url, sp.discoveredAt = datetime()
WITH sp
MATCH (e:TDCEmail {contentHash: $email_hash})
MERGE (e)-[:CONTAINS_LINK]->(sp)
""",
hash=link_hash,
url=sp_link,
email_hash=content_hash
)
def save_sharepoint_link(self, url: str):
"""Gem SharePoint link separat"""
link_hash = hashlib.md5(url.encode()).hexdigest()
with self.neo4j.session() as session:
session.run("""
MERGE (sp:SharePointLink {contentHash: $hash})
ON CREATE SET
sp.url = $url,
sp.discoveredAt = datetime(),
sp.source = 'email_extraction'
""",
hash=link_hash,
url=url
)
def run(self):
"""Kør fuld harvest"""
print("\n" + "=" * 60)
print("📧 TDC OUTLOOK/EXCHANGE HARVESTER")
print("=" * 60)
# 1. List folders
print("\n📁 AVAILABLE FOLDERS")
folders = self.get_folders()
# 2. Harvest inbox
inbox_results = self.harvest_inbox(days_back=180, max_per_term=50)
# 3. Harvest sent items
sent_results = self.harvest_sent_items(max_per_term=30)
# 4. Extract SharePoint links
sp_links = self.extract_sharepoint_links()
# 5. Summary
print("\n" + "=" * 60)
print("📊 HARVEST COMPLETE")
print("=" * 60)
print(f" 📧 Emails scanned: ~{self.stats['emails_scanned']}")
print(f" ✅ Relevant emails: {self.stats['relevant_emails']}")
print(f" 🔗 SharePoint links: {self.stats['sharepoint_links']}")
print(f" 📎 With attachments: {sum(1 for e in self.emails if e.get('has_attachments'))}")
print("=" * 60)
# Save local JSON
output_file = self.output_dir / "outlook_harvest.json"
with open(output_file, 'w', encoding='utf-8') as f:
json.dump({
"timestamp": datetime.now().isoformat(),
"stats": self.stats,
"emails": self.emails[:200],
"sharepoint_links": list(set(self.sharepoint_links))[:100]
}, f, indent=2, ensure_ascii=False, default=str)
print(f"\n📁 Results saved: {output_file}")
# Cleanup
pythoncom.CoUninitialize()
self.neo4j.close()
return self.emails, sp_links
if __name__ == "__main__":
harvester = TDCOutlookHarvester()
harvester.run()
|