I'll help you create a Python email AI agent that processes PDFs and integrates with MYOB EXO. Here's a comprehensive solution:
import imaplib
import email
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import os
import requests
import json
from dataclasses import dataclass
from typing import List, Optional, Dict, Any
import logging
from datetime import datetime
import re
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class SalesOrderData:
customer_name: str
customer_email: str
items: List[Dict[str, Any]]
total_amount: float
order_date: str
reference_number: Optional[str] = None
shipping_address: Optional[str] = None
billing_address: Optional[str] = None
class EmailAgent:
def __init__(self, email_config: Dict[str, str]):
self.email_config = email_config
self.imap_server = None
self.smtp_server = None
def connect_imap(self):
"""Connect to IMAP server"""
try:
self.imap_server = imaplib.IMAP4_SSL(self.email_config['imap_host'])
self.imap_server.login(self.email_config['username'], self.email_config['password'])
logger.info("Successfully connected to IMAP server")
except Exception as e:
logger.error(f"Failed to connect to IMAP: {e}")
raise
def search_emails_with_pdf_attachments(self, label: str) -> List[Dict]:
"""Search for emails with PDF attachments in specified label"""
if not self.imap_server:
self.connect_imap()
try:
# Select the mailbox/label
self.imap_server.select(label)
# Search for emails with attachments
status, messages = self.imap_server.search(None, 'ALL')
email_ids = messages[0].split()
emails_with_pdfs = []
for email_id in email_ids:
status, msg_data = self.imap_server.fetch(email_id, '(RFC822)')
email_message = email.message_from_bytes(msg_data[0][1])
pdf_attachments = self._extract_pdf_attachments(email_message)
if pdf_attachments:
emails_with_pdfs.append({
'email_id': email_id,
'email_message': email_message,
'pdf_attachments': pdf_attachments,
'subject': email_message['Subject'],
'from': email_message['From'],
'date': email_message['Date']
})
logger.info(f"Found {len(emails_with_pdfs)} emails with PDF attachments")
return emails_with_pdfs
except Exception as e:
logger.error(f"Error searching emails: {e}")
return []
def _extract_pdf_attachments(self, email_message) -> List[Dict]:
"""Extract PDF attachments from email"""
pdf_attachments = []
for part in email_message.walk():
if part.get_content_disposition() == 'attachment':
filename = part.get_filename()
if filename and filename.lower().endswith('.pdf'):
pdf_attachments.append({
'filename': filename,
'content': part.get_payload(decode=True)
})
return pdf_attachments
class LlamaParseClient:
def __init__(self, api_key: str, base_url: str = "https://api.llamaindex.ai"):
self.api_key = api_key
self.base_url = base_url
self.headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
def parse_pdf(self, pdf_content: bytes, filename: str) -> str:
"""Send PDF to Llama Parse and get markdown content"""
try:
# Save PDF temporarily
temp_pdf_path = f"/tmp/{filename}"
with open(temp_pdf_path, 'wb') as f:
f.write(pdf_content)
# Upload to Llama Parse
with open(temp_pdf_path, 'rb') as f:
files = {'file': (filename, f, 'application/pdf')}
response = requests.post(
f"{self.base_url}/parsing/upload",
headers={'Authorization': f'Bearer {self.api_key}'},
files=files
)
if response.status_code == 200:
job_id = response.json()['id']
return self._get_parsing_result(job_id)
else:
logger.error(f"Failed to upload PDF: {response.text}")
return ""
except Exception as e:
logger.error(f"Error parsing PDF: {e}")
return ""
finally:
# Clean up temp file
if os.path.exists(temp_pdf_path):
os.remove(temp_pdf_path)
def _get_parsing_result(self, job_id: str) -> str:
"""Get parsing result from Llama Parse"""
import time
max_attempts = 30
for attempt in range(max_attempts):
try:
response = requests.get(
f"{self.base_url}/parsing/job/{job_id}",
headers=self.headers
)
if response.status_code == 200:
result = response.json()
if result['status'] == 'SUCCESS':
return result['result']['markdown']
elif result['status'] == 'FAILED':
logger.error(f"Parsing failed: {result.get('error', 'Unknown error')}")
return ""
else:
time.sleep(2) # Wait before checking again
else:
logger.error(f"Error checking job status: {response.text}")
return ""
except Exception as e:
logger.error(f"Error getting parsing result: {e}")
return ""
logger.error("Parsing timeout")
return ""
class DataCleanupAgent:
def __init__(self):
self.sales_keywords = [
'invoice', 'order', 'purchase', 'quote', 'quotation',
'total', 'amount', 'price', 'cost', 'quantity', 'qty'
]
def clean_and_extract_sales_data(self, markdown_content: str, email_info: Dict) -> Optional[SalesOrderData]:
"""Clean markdown content and extract sales order information"""
try:
# Remove unnecessary formatting and clean up
cleaned_content = self._clean_markdown(markdown_content)
# Extract structured data
extracted_data = self._extract_sales_information(cleaned_content)
if extracted_data:
return SalesOrderData(
customer_name=self._extract_customer_name(email_info['from']),
customer_email=self._extract_email_address(email_info['from']),
items=extracted_data.get('items', []),
total_amount=extracted_data.get('total_amount', 0.0),
order_date=email_info['date'],
reference_number=extracted_data.get('reference_number'),
shipping_address=extracted_data.get('shipping_address'),
billing_address=extracted_data.get('billing_address')
)
return None
except Exception as e:
logger.error(f"Error cleaning and extracting data: {e}")
return None
def _clean_markdown(self, content: str) -> str:
"""Remove unnecessary markdown formatting and clean up content"""
# Remove excessive whitespace
content = re.sub(r'\n\s*\n', '\n\n', content)
# Remove markdown formatting that's not needed
content = re.sub(r'\*\*\*', '', content)
content = re.sub(r'---+', '', content)
# Keep only relevant sections
lines = content.split('\n')
relevant_lines = []
for line in lines:
line = line.strip()
if any(keyword.lower() in line.lower() for keyword in self.sales_keywords):
relevant_lines.append(line)
elif re.search(r'\$[\d,]+\.?\d*|\d+\.\d{2}|qty|quantity', line.lower()):
relevant_lines.append(line)
return '\n'.join(relevant_lines)
def _extract_sales_information(self, content: str) -> Dict[str, Any]:
"""Extract structured sales information from cleaned content"""
data = {
'items': [],
'total_amount': 0.0,
'reference_number': None,
'shipping_address': None,
'billing_address': None
}
# Extract total amount
total_matches = re.findall(r'total[:\s]*\$?([\d,]+\.?\d*)', content, re.IGNORECASE)
if total_matches:
data['total_amount'] = float(total_matches[-1].replace(',', ''))
# Extract reference/order number
ref_matches = re.findall(r'(?:order|invoice|ref|reference)[#\s:]*([A-Z0-9-]+)', content, re.IGNORECASE)
if ref_matches:
data['reference_number'] = ref_matches[0]
# Extract line items (simplified pattern)
item_pattern = r'(.+?)\s+(\d+)\s+\$?([\d,]+\.?\d*)'
items = re.findall(item_pattern, content)
for item_match in items:
description, quantity, price = item_match
data['items'].append({
'description': description.strip(),
'quantity': int(quantity),
'unit_price': float(price.replace(',', '')),
'total_price': int(quantity) * float(price.replace(',', ''))
})
return data
def _extract_customer_name(self, from_field: str) -> str:
"""Extract customer name from email from field"""
match = re.match(r'(.+?)\s*<.+>', from_field)
if match:
return match.group(1).strip().strip('"')
return from_field.split('@')[0]
def _extract_email_address(self, from_field: str) -> str:
"""Extract email address from from field"""
match = re.search(r'<(.+?)>', from_field)
if match:
return match.group(1)
return from_field
class MYOBEXOIntegration:
def __init__(self, myob_config: Dict[str, str]):
self.myob_config = myob_config
self.base_url = myob_config.get('base_url')
self.headers = {
'Authorization': f'Bearer {myob_config.get("access_token")}',
'Content-Type': 'application/json'
}
def create_sales_order(self, sales_data: SalesOrderData, approved: bool = False) -> Dict[str, Any]:
"""Create sales order in MYOB EXO"""
if not approved:
logger.info("Sales order requires human approval before creation")
return {'status': 'pending_approval', 'data': sales_data}
try:
# Prepare MYOB EXO sales order payload
order_payload = {
'CustomerCode': self._get_or_create_customer(sales_data),
'OrderDate': sales_data.order_date,
'Reference': sales_data.reference_number,
'Lines': []
}
# Add line items
for item in sales_data.items:
order_payload['Lines'].append({
'ProductCode': self._map_product_code(item['description']),
'Description': item['description'],
'Quantity': item['quantity'],
'UnitPrice': item['unit_price']
})
# Create order in MYOB EXO
response = requests.post(
f"{self.base_url}/api/salesorders",
headers=self.headers,
json=order_payload
)
if response.status_code == 201:
logger.info(f"Sales order created successfully: {response.json()}")
return {'status': 'success', 'order_id': response.json().get('OrderNumber')}
else:
logger.error(f"Failed to create sales order: {response.text}")
return {'status': 'error', 'message': response.text}
except Exception as e:
logger.error(f"Error creating sales order: {e}")
return {'status': 'error', 'message': str(e)}
def _get_or_create_customer(self, sales_data: SalesOrderData) -> str:
"""Get existing customer or create new one"""
# Check if customer exists
response = requests.get(
f"{self.base_url}/api/customers",
headers=self.headers,
params={'email': sales_data.customer_email}
)
if response.status_code == 200 and response.json():
return response.json()[0]['CustomerCode']
# Create new customer
customer_payload = {
'Name': sales_data.customer_name,
'Email': sales_data.customer_email,
'CustomerCode': self._generate_customer_code(sales_data.customer_name)
}
response = requests.post(
f"{self.base_url}/api/customers",
headers=self.headers,
json=customer_payload
)
if response.status_code == 201:
return response.json()['CustomerCode']
raise Exception(f"Failed to create customer: {response.text}")
def _generate_customer_code(self, customer_name: str) -> str:
"""Generate customer code from name"""
return ''.join(word[:3].upper() for word in customer_name.split()[:2])
def _map_product_code(self, description: str) -> str:
"""Map product description to MYOB product code"""
# This would typically involve a lookup table or AI matching
# For now, return a default or generate based on description
return f"PROD_{description[:10].upper().replace(' ', '_')}"
class SalesOrderProcessor:
def __init__(self, email_config: Dict, llama_config: Dict, myob_config: Dict):
self.email_agent = EmailAgent(email_config)
self.llama_client = LlamaParseClient(llama_config['api_key'])
self.cleanup_agent = DataCleanupAgent()
self.myob_integration = MYOBEXOIntegration(myob_config)
self.pending_approvals = []
def process_emails(self, label: str = "INBOX"):
"""Main processing function"""
logger.info("Starting email processing...")
# Step 1: Search for emails with PDF attachments
emails_with_pdfs = self.email_agent.search_emails_with_pdf_attachments(label)
for email_data in emails_with_pdfs:
logger.info(f"Processing email: {email_data['subject']}")
for pdf_attachment in email_data['pdf_attachments']:
# Step 2: Parse PDF with Llama Parse
markdown_content = self.ll