0
# Email and Messaging
1
2
Complete email management including inbox access, message composition, folder operations, attachment handling, and search capabilities with support for shared mailboxes.
3
4
## Capabilities
5
6
### Mailbox Access
7
8
Access mailboxes for the authenticated user or other users (with proper permissions).
9
10
```python { .api }
11
def mailbox(self, resource: str = None) -> MailBox:
12
"""
13
Get a mailbox instance.
14
15
Parameters:
16
- resource: user resource identifier (defaults to authenticated user)
17
18
Returns:
19
- MailBox: Mailbox instance for email operations
20
"""
21
22
class MailBox:
23
def __init__(self, parent: Account, main_resource: str = None): ...
24
25
# Well-known folder shortcuts
26
def inbox_folder(self) -> Folder:
27
"""Get the inbox folder."""
28
29
def sent_folder(self) -> Folder:
30
"""Get the sent items folder."""
31
32
def drafts_folder(self) -> Folder:
33
"""Get the drafts folder."""
34
35
def deleted_folder(self) -> Folder:
36
"""Get the deleted items folder."""
37
38
def junk_folder(self) -> Folder:
39
"""Get the junk email folder."""
40
41
def outbox_folder(self) -> Folder:
42
"""Get the outbox folder."""
43
44
def archive_folder(self) -> Folder:
45
"""Get the archive folder."""
46
47
def clutter_folder(self) -> Folder:
48
"""Get the clutter folder."""
49
50
def conflicts_folder(self) -> Folder:
51
"""Get the conflicts folder."""
52
53
def conversationhistory_folder(self) -> Folder:
54
"""Get the conversation history folder."""
55
56
def localfailures_folder(self) -> Folder:
57
"""Get the local failures folder."""
58
59
def recoverableitemsdeletions_folder(self) -> Folder:
60
"""Get the recoverable items deletions folder."""
61
62
def scheduled_folder(self) -> Folder:
63
"""Get the scheduled folder."""
64
65
def searchfolders_folder(self) -> Folder:
66
"""Get the search folders folder."""
67
68
def serverfailures_folder(self) -> Folder:
69
"""Get the server failures folder."""
70
71
def syncissues_folder(self) -> Folder:
72
"""Get the sync issues folder."""
73
74
# Message operations
75
def get_messages(self, limit: int = 25, *, query=None, order_by=None, batch=None, download_attachments: bool = False) -> list[Message]: ...
76
def get_message(self, object_id: str = None, query=None, *, download_attachments: bool = False) -> Message: ...
77
def new_message(self) -> Message: ...
78
def delete_message(self, message): ...
79
80
# Folder operations
81
def get_folders(self, limit: int = None, *, query=None, order_by=None, batch=None) -> list[Folder]: ...
82
def get_folder(self, *, folder_id: str = None, folder_name: str = None) -> Folder: ...
83
def create_child_folder(self, folder_name: str) -> Folder: ...
84
def refresh_folder(self, update_parent_if_changed: bool = False) -> bool: ...
85
def update_folder_name(self, name: str, update_folder_data: bool = True) -> bool: ...
86
def delete(self) -> bool: ...
87
def copy_folder(self, to_folder: Folder) -> Folder: ...
88
def move_folder(self, to_folder: Folder, *, update_parent_if_changed: bool = True) -> bool: ...
89
90
# Mailbox settings
91
def get_settings(self) -> MailboxSettings: ...
92
def set_automatic_reply(self, internal_text: str, external_text: str,
93
scheduled_start_date_time=None, scheduled_end_date_time=None,
94
externalAudience=None) -> bool: ...
95
def set_disable_reply(self) -> bool: ...
96
```
97
98
### Folder Management
99
100
Manage email folders including creation, deletion, and navigation.
101
102
```python { .api }
103
def get_folders(self, limit: int = None, **filters) -> list[Folder]:
104
"""
105
Get mailbox folders.
106
107
Parameters:
108
- limit: maximum number of folders to return
109
- filters: additional OData filters
110
111
Returns:
112
- list[Folder]: List of folder objects
113
"""
114
115
def get_folder(self, folder_id: str = None, folder_name: str = None) -> Folder:
116
"""
117
Get a specific folder by ID or name.
118
119
Parameters:
120
- folder_id: folder identifier
121
- folder_name: folder display name
122
123
Returns:
124
- Folder: Folder object
125
"""
126
127
def new_folder(self, folder_name: str, parent_folder: Folder = None) -> Folder:
128
"""
129
Create a new folder.
130
131
Parameters:
132
- folder_name: name for the new folder
133
- parent_folder: parent folder (defaults to root)
134
135
Returns:
136
- Folder: Created folder object
137
"""
138
139
class Folder:
140
@property
141
def name(self) -> str:
142
"""Folder display name."""
143
144
@property
145
def total_item_count(self) -> int:
146
"""Total number of items in folder."""
147
148
@property
149
def unread_item_count(self) -> int:
150
"""Number of unread items in folder."""
151
152
def get_messages(self, limit: int = None, **filters) -> list[Message]:
153
"""Get messages from this folder."""
154
155
def move_to(self, to_folder: 'Folder') -> bool:
156
"""Move this folder to another parent folder."""
157
158
def delete(self) -> bool:
159
"""Delete this folder."""
160
```
161
162
### Message Operations
163
164
Retrieve, create, send, and manage email messages.
165
166
```python { .api }
167
def get_messages(self, limit: int = None, download_attachments: bool = False, **filters) -> list[Message]:
168
"""
169
Get messages from the mailbox.
170
171
Parameters:
172
- limit: maximum number of messages to return
173
- download_attachments: whether to download message attachments
174
- filters: OData query filters (subject, sender, received_time, etc.)
175
176
Returns:
177
- list[Message]: List of message objects
178
"""
179
180
def new_message(self, to_recipients: list = None,
181
cc_recipients: list = None,
182
bcc_recipients: list = None) -> Message:
183
"""
184
Create a new message.
185
186
Parameters:
187
- to_recipients: list of recipient email addresses or Recipient objects
188
- cc_recipients: list of CC recipients
189
- bcc_recipients: list of BCC recipients
190
191
Returns:
192
- Message: New message object
193
"""
194
195
class Message:
196
@property
197
def subject(self) -> str:
198
"""Message subject line."""
199
200
@property
201
def body(self) -> str:
202
"""Message body content."""
203
204
@property
205
def sender(self) -> Recipient:
206
"""Message sender information."""
207
208
@property
209
def to_recipients(self) -> Recipients:
210
"""To recipients collection."""
211
212
@property
213
def received_time(self) -> datetime:
214
"""When the message was received."""
215
216
@property
217
def is_read(self) -> bool:
218
"""Whether the message has been read."""
219
220
@property
221
def importance(self) -> str:
222
"""Message importance level (Low, Normal, High)."""
223
224
def send(self) -> bool:
225
"""Send the message."""
226
227
def reply(self, to_all: bool = True) -> Message:
228
"""Create a reply to this message."""
229
230
def forward(self) -> Message:
231
"""Create a forward of this message."""
232
233
def mark_as_read(self) -> bool:
234
"""Mark the message as read."""
235
236
def mark_as_unread(self) -> bool:
237
"""Mark the message as unread."""
238
239
def delete(self) -> bool:
240
"""Delete this message."""
241
242
def move_to(self, folder: Folder) -> bool:
243
"""Move message to a specific folder."""
244
```
245
246
### Attachment Handling
247
248
Manage email attachments including upload, download, and inline attachments.
249
250
```python { .api }
251
class MessageAttachments:
252
def __iter__(self) -> Iterator[MessageAttachment]:
253
"""Iterate over attachments."""
254
255
def download_attachments(self, to_path: str = None) -> bool:
256
"""
257
Download all attachments.
258
259
Parameters:
260
- to_path: directory to save attachments (defaults to current directory)
261
262
Returns:
263
- bool: True if all downloads successful
264
"""
265
266
def add(self, attachments: list) -> bool:
267
"""Add attachments to the message."""
268
269
class MessageAttachment:
270
@property
271
def name(self) -> str:
272
"""Attachment filename."""
273
274
@property
275
def size(self) -> int:
276
"""Attachment size in bytes."""
277
278
@property
279
def content_type(self) -> str:
280
"""MIME content type."""
281
282
@property
283
def is_inline(self) -> bool:
284
"""Whether attachment is inline."""
285
286
def download(self, to_path: str = None) -> str:
287
"""
288
Download the attachment.
289
290
Parameters:
291
- to_path: path to save the file
292
293
Returns:
294
- str: path to downloaded file
295
"""
296
```
297
298
### Search and Filtering
299
300
Advanced message search and filtering capabilities.
301
302
```python { .api }
303
def search(self, search_text: str, folder: Folder = None) -> list[Message]:
304
"""
305
Search for messages.
306
307
Parameters:
308
- search_text: text to search for in subject/body
309
- folder: folder to search in (defaults to all folders)
310
311
Returns:
312
- list[Message]: Matching messages
313
"""
314
315
# Common filter examples for get_messages()
316
# By sender: sender='user@domain.com'
317
# By subject: subject__contains='Meeting'
318
# By date: received_time__gte=datetime(2023, 1, 1)
319
# Unread only: is_read=False
320
# With attachments: has_attachments=True
321
```
322
323
### Message Categories and Flags
324
325
Organize messages with categories and flags.
326
327
```python { .api }
328
class Message:
329
@property
330
def categories(self) -> list[str]:
331
"""Message categories."""
332
333
@property
334
def flag(self) -> dict:
335
"""Message flag information."""
336
337
def add_category(self, category: str) -> bool:
338
"""Add a category to the message."""
339
340
def remove_category(self, category: str) -> bool:
341
"""Remove a category from the message."""
342
343
def flag_message(self, flag_status: str = 'flagged') -> bool:
344
"""
345
Flag the message.
346
347
Parameters:
348
- flag_status: 'flagged', 'complete', or 'notFlagged'
349
350
Returns:
351
- bool: True if successful
352
"""
353
```
354
355
## Usage Examples
356
357
### Basic Email Operations
358
359
```python
360
from O365 import Account
361
362
account = Account(credentials)
363
mailbox = account.mailbox()
364
365
# Read recent emails
366
inbox = mailbox.inbox_folder
367
messages = inbox.get_messages(limit=10)
368
369
for message in messages:
370
print(f"From: {message.sender.address}")
371
print(f"Subject: {message.subject}")
372
print(f"Received: {message.received_time}")
373
print(f"Read: {message.is_read}")
374
print("---")
375
```
376
377
### Send Email with Attachments
378
379
```python
380
# Create and send a new message
381
message = mailbox.new_message()
382
message.to_recipients.add('recipient@example.com')
383
message.subject = 'Test Message'
384
message.body = 'Hello from O365 Python library!'
385
386
# Add attachments
387
message.attachments.add(['document.pdf', 'image.jpg'])
388
389
# Send the message
390
if message.send():
391
print('Message sent successfully')
392
```
393
394
### Advanced Message Search
395
396
```python
397
from datetime import datetime, timedelta
398
399
# Search for unread messages from last week
400
last_week = datetime.now() - timedelta(days=7)
401
recent_unread = inbox.get_messages(
402
is_read=False,
403
received_time__gte=last_week,
404
limit=50
405
)
406
407
# Search for messages with specific subject
408
meeting_messages = inbox.get_messages(
409
subject__contains='Meeting',
410
limit=20
411
)
412
413
# Search messages from specific sender
414
sender_messages = inbox.get_messages(
415
sender='manager@company.com'
416
)
417
```
418
419
### Folder Management
420
421
```python
422
# Create a new folder
423
projects_folder = mailbox.new_folder('Projects')
424
425
# Move messages to folder
426
for message in messages:
427
if 'project' in message.subject.lower():
428
message.move_to(projects_folder)
429
430
# Get folder statistics
431
print(f"Total items: {projects_folder.total_item_count}")
432
print(f"Unread items: {projects_folder.unread_item_count}")
433
```
434
435
## Types
436
437
```python { .api }
438
# Mailbox settings classes
439
class MailboxSettings:
440
automaticrepliessettings: AutomaticRepliesSettings
441
timezone: str
442
workinghours: dict
443
444
class AutomaticRepliesSettings:
445
external_reply_message: str
446
internal_reply_message: str
447
scheduled_start_date_time: datetime
448
scheduled_end_date_time: datetime
449
status: str # AutoReplyStatus
450
external_audience: str # ExternalAudience
451
452
# Enums for mailbox settings
453
class ExternalAudience:
454
NONE = "none"
455
CONTACTSONLY = "contactsOnly"
456
ALL = "all"
457
458
class AutoReplyStatus:
459
DISABLED = "disabled"
460
ALWAYSENABLED = "alwaysEnabled"
461
SCHEDULED = "scheduled"
462
463
# Message-related enums
464
class RecipientType:
465
TO = "to"
466
CC = "cc"
467
BCC = "bcc"
468
469
class Flag:
470
NOT_FLAGGED = "notFlagged"
471
COMPLETE = "complete"
472
FLAGGED = "flagged"
473
474
class Importance:
475
LOW = "low"
476
NORMAL = "normal"
477
HIGH = "high"
478
479
class MeetingMessageType:
480
NONE = "none"
481
MEETING_REQUEST = "meetingRequest"
482
MEETING_CANCELLED = "meetingCancelled"
483
MEETING_ACCEPTED = "meetingAccepted"
484
MEETING_TENTATIVELY_ACCEPTED = "meetingTentativelyAccepted"
485
MEETING_DECLINED = "meetingDeclined"
486
```