starts work on recent emails.
This commit is contained in:
@@ -80,6 +80,17 @@ class User(Base, UserMixin):
|
||||
# ... existing fields ...
|
||||
```
|
||||
|
||||
### Folder Model Updates
|
||||
|
||||
The `Folder` model now includes a new field for storing recent email information:
|
||||
|
||||
```python
|
||||
class Folder(Base):
|
||||
# ... existing fields ...
|
||||
recent_emails = db.Column(db.JSON, default=list) # Store recent email subjects with dates
|
||||
# ... existing fields ...
|
||||
```
|
||||
|
||||
### IMAP Configuration Structure
|
||||
|
||||
```json
|
||||
@@ -267,6 +278,83 @@ class IMAPService:
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
return False, f"Sync error: {str(e)}"
|
||||
|
||||
def get_recent_emails(self, folder_name: str, limit: int = 3) -> List[Dict[str, any]]:
|
||||
"""Get the most recent email subjects and dates from a specific folder."""
|
||||
try:
|
||||
# Connect to IMAP server
|
||||
self._connect()
|
||||
|
||||
# Login
|
||||
self.connection.login(
|
||||
self.config.get('username', ''),
|
||||
self.config.get('password', '')
|
||||
)
|
||||
|
||||
# Select the folder
|
||||
resp_code, content = self.connection.select(folder_name)
|
||||
if resp_code != 'OK':
|
||||
return []
|
||||
|
||||
# Get email IDs (most recent first)
|
||||
resp_code, content = self.connection.search(None, 'ALL')
|
||||
if resp_code != 'OK':
|
||||
return []
|
||||
|
||||
# Get the most recent emails (limit to 3)
|
||||
email_ids = content[0].split()
|
||||
recent_email_ids = email_ids[:limit] if len(email_ids) >= limit else email_ids
|
||||
|
||||
recent_emails = []
|
||||
for email_id in reversed(recent_email_ids): # Process from newest to oldest
|
||||
# Fetch the email headers
|
||||
resp_code, content = self.connection.fetch(email_id, '(RFC822.HEADER)')
|
||||
if resp_code != 'OK':
|
||||
continue
|
||||
|
||||
# Parse the email headers
|
||||
raw_email = content[0][1]
|
||||
import email
|
||||
msg = email.message_from_bytes(raw_email)
|
||||
|
||||
# Extract subject and date
|
||||
subject = msg.get('Subject', 'No Subject')
|
||||
date_str = msg.get('Date', '')
|
||||
|
||||
# Decode the subject if needed
|
||||
try:
|
||||
decoded_parts = decode_header(subject)
|
||||
subject = ''.join([str(part, encoding or 'utf-8') if isinstance(part, bytes) else part for part, encoding in decoded_parts])
|
||||
except Exception:
|
||||
pass # If decoding fails, use the original subject
|
||||
|
||||
# Parse date if available
|
||||
try:
|
||||
email_date = parsedate_to_datetime(date_str) if date_str else None
|
||||
except Exception:
|
||||
email_date = None
|
||||
|
||||
recent_emails.append({
|
||||
'subject': subject,
|
||||
'date': email_date.isoformat() if email_date else None
|
||||
})
|
||||
|
||||
# Close folder and logout
|
||||
self.connection.close()
|
||||
self.connection.logout()
|
||||
self.connection = None
|
||||
|
||||
return recent_emails
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"Error getting recent emails for folder {folder_name}: {str(e)}")
|
||||
if self.connection:
|
||||
try:
|
||||
self.connection.logout()
|
||||
except:
|
||||
pass
|
||||
self.connection = None
|
||||
return []
|
||||
```
|
||||
|
||||
## Routes Implementation
|
||||
|
||||
Reference in New Issue
Block a user