Metadata-Version: 2.4
Name: onedevcommonmsgraph
Version: 1.0.2
Summary: Biblioteca para integração com Microsoft Graph API
Project-URL: Homepage, https://github.com/onedev/onedev-common-ms-graph
Project-URL: Repository, https://github.com/onedev/onedev-common-ms-graph.git
Project-URL: Documentation, https://github.com/onedev/onedev-common-ms-graph#readme
Author-email: Marcus Simas <marcus.simas@ufly.com.br>
License-Expression: MIT
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.8
Requires-Dist: msal>=1.25.0
Requires-Dist: requests>=2.31.0
Description-Content-Type: text/markdown

# OnedevCommon MS Graph

Python library for Microsoft Graph API integration, focused on sending and analyzing emails for shared mailboxes.

## 📋 Overview

This library offers complete functionality for:
- ✉️ **Email sending** via Microsoft Graph API
- 📧 **Email reading** from shared mailboxes
- 📊 **Advanced email analysis** with multiple configuration options
- 💾 **Automatic saving** of results in JSON format

## 🗂️ Project Structure

```
onedev-common-ms-graph/
├── onedevcommonmsgraph/
│   ├── __init__.py              # Package initialization
│   ├── email_.py                # 📤 Email sending
│   ├── email_reader.py          # 📥 Email reading (core)
│   ├── email_analyzer.py        # 📊 Advanced email analysis
│   └── logs/
│       └── .gitkeep            # Keeps folder in repository
├── setup.py                    # Installation configuration
├── pyproject.toml              # Project metadata
└── README.md                   # This documentation
```

## 📁 File Description

### 📤 `email_.py` - Email Sending
**Function:** Sends emails via Microsoft Graph API to shared mailboxes.

**Features:**
- Automatic authentication with Azure AD
- Support for multiple recipients (TO, CC, BCC)
- Attachment sending
- Priority and importance configuration
- HTML and plain text formatting

**Main usage:** 
```python
from onedevcommonmsgraph.email_ import EmailSender
sender = EmailSender(tenant_id, client_id, client_secret, from_email)
sender.send_email(to=["destination@example.com"], subject="Subject", body="Content")
```

---

### 📥 `email_reader.py` - Email Reading (Core)
**Function:** Simplified base class for reading emails via Microsoft Graph API.

**Main methods:**
- `list_emails(limit, filter_query)` - Lists emails with filters
- `read_detailed_email(email_id)` - Reads specific email with complete details
- `list_unread_emails()` - Lists only unread emails
- `list_emails_period(days)` - Lists emails from a specific period
- `mark_as_read(email_id)` - Marks email as read

**Main usage:**
```python
from onedevcommonmsgraph.email_reader import EmailReader
reader = EmailReader(tenant_id, client_id, client_secret, email_box)
emails = reader.list_emails(limit=10)
```

---

### 📊 `email_analyzer.py` - Advanced Email Analysis
**Function:** Configurable and advanced email analysis with automatic JSON saving.

**Supported Email Types:**
- `'all'` - All emails
- `'latest'` - Latest N emails
- `'unread'` - Only unread emails  
- `'period'` - Emails from a specific period
- `'by_sender'` - Emails from specific sender
- `'by_subject'` - Emails with term in subject

**Information Types Extracted:**
- `'all'` - All available information
- `'basic'` - Basic information (ID, subject, sender, date)
- `'status'` - Email status (read/unread, attachments)
- `'senders'` - Only sender information
- `'content'` - Email content
- `'attachments'` - Attachment information
- `'summary'` - Executive summary
- `[custom list]` - Specific fields defined by user

**Features:**
- 🎯 **Flexible configuration** - Combine any email type with any information type
- 📊 **Automatic statistics** - Read rate, top senders, emails with attachments
- 💾 **Automatic saving** - JSON files with unique timestamp in `logs/`
- 📈 **Progress reports** - Real-time processing tracking
- 🔧 **Custom fields** - Extract only the information you need

**Main usage:**
```python
from onedevcommonmsgraph.email_analyzer import EmailAnalyzer
analyzer = EmailAnalyzer(tenant_id, client_id, client_secret, email_box)

# Analysis of latest 5 emails with basic information
result = analyzer.analyze_emails(
    email_type='latest',
    information_to_extract='basic',
    parameters={'limit': 5}
)

# Analysis of unread emails with complete information
result = analyzer.analyze_emails(
    email_type='unread',
    information_to_extract='all'
)

# Analysis with custom fields
result = analyzer.analyze_emails(
    email_type='period',
    information_to_extract=['subject', 'sender', 'status'],
    parameters={'days': 7}
)
```

---

### 📁 `logs/` - Logs Folder
**Function:** Automatically stores JSON files generated by EmailAnalyzer.

**Content:**
- `email_analysis_YYYYMMDD_HHMMSS.json` - Analysis results with unique timestamp
- `.gitkeep` - Keeps folder in Git repository even when empty

**Features:**
- ✅ **Automatic creation** - Folder created automatically if it doesn't exist
- ✅ **Unique timestamps** - Each analysis generates file with unique date/time
- ✅ **Git preservation** - Folder maintained in repository via `.gitkeep`
- ✅ **Safe cleanup** - Can delete logs without affecting functionality

## 🚀 Installation and Configuration

### Prerequisites
```bash
pip install requests
```

### Azure AD Configuration
1. Register an application in Azure AD
2. Configure necessary permissions:
   - `Mail.Send` (for sending)
   - `Mail.Read` (for reading)
   - `Mail.ReadWrite` (for marking as read)
3. Obtain credentials:
   - `tenant_id` - Tenant ID
   - `client_id` - Application ID
   - `client_secret` - Application secret

## 📋 Usage Examples

### Email Sending
```python
from onedevcommonmsgraph.email_ import EmailSender

sender = EmailSender(tenant_id, client_id, client_secret, "sender@company.com")
sender.send_email(
    to=["destination@example.com"],
    subject="Email Subject",
    body="<h1>HTML Content</h1>"
)
```

### Simple Reading
```python
from onedevcommonmsgraph.email_reader import EmailReader

reader = EmailReader(tenant_id, client_id, client_secret, "mailbox@company.com")
emails = reader.list_emails(limit=10)
unread = reader.list_unread_emails()
```

### Advanced Analysis
```python
from onedevcommonmsgraph.email_analyzer import EmailAnalyzer

analyzer = EmailAnalyzer(tenant_id, client_id, client_secret, "mailbox@company.com")

# Complete analysis of latest 50 emails
result = analyzer.analyze_emails(
    email_type='latest',
    information_to_extract='all',
    parameters={'limit': 50}
)

# Result automatically saved in logs/email_analysis_YYYYMMDD_HHMMSS.json
print(f"Analysis saved to: {result['saved_file']}")
print(f"Total emails: {result['total_emails']}")
print(f"Statistics: {result['statistics']}")
```

## 🔧 Advanced Settings

### EmailAnalyzer Parameters
- `email_type`: Defines which emails to analyze
- `information_to_extract`: Defines which information to extract
- `parameters`: Specific parameters (limit, days, sender, etc.)
- `save_file`: Whether to save automatically (default: True)

### Result JSON Structure
```json
{
  "success": true,
  "configuration": {
    "email_type": "latest",
    "information_extracted": "all",
    "parameters": {"limit": 10}
  },
  "total_emails": 10,
  "emails": [...],
  "statistics": {
    "read_rate": 85.5,
    "emails_with_attachments": 3,
    "top_senders": [...]
  },
  "analysis_timestamp": "2024-06-18T11:25:19.978831",
  "saved_file": "logs/email_analysis_20240618_112519.json"
}
```

## 📊 Use Cases

1. **📧 Shared Mailbox Monitoring**
   - Automatically analyze unread emails
   - Generate team activity reports

2. **📈 Communication Analysis**
   - Identify top senders
   - Analyze communication patterns

3. **🔍 Search and Filtering**
   - Find emails by specific sender
   - Filter by period or subject

4. **📋 Automated Reports**
   - Generate automatic JSON reports

## 🤝 Contributing

This project is part of the uFly ecosystem and is constantly evolving. For suggestions or improvements, contact the development team.
