MS365 Notifier Documentation

MS365 Notifier is a powerful Python library for sending notifications across Microsoft 365 services including Teams, Outlook, and SharePoint. Built on top of Microsoft Graph API, it provides a simple and intuitive interface for integrating notifications into your Python applications.

🚀 Easy to Use

Simple API with sensible defaults. Get started with just a few lines of code.

🔐 Secure Authentication

Support for multiple authentication methods including OAuth2 and service principals.

📨 Multi-Channel

Send notifications to Teams channels, Outlook emails, and SharePoint sites.

⚡ Async Support

Full async/await support for high-performance applications.

Installation

Install MS365 Notifier using pip:

pip install ms365-notifier

Or with optional dependencies for enhanced features:

pip install ms365-notifier[templates,async]

Quick Start

Here's a simple example to send a notification to a Teams channel:

from ms365_notifier import Notifier # Initialize the notifier with your credentials notifier = Notifier( client_id="your-client-id", client_secret="your-client-secret", tenant_id="your-tenant-id" ) # Send a simple message to Teams notifier.teams.send_message( channel_id="your-channel-id", message="Hello from MS365 Notifier! 🎉" )

Authentication

MS365 Notifier supports multiple authentication methods to fit your use case:

OAuth2 Authentication

Use OAuth2 for interactive applications where users log in with their Microsoft accounts:

from ms365_notifier import Notifier, OAuth2Config config = OAuth2Config( client_id="your-client-id", redirect_uri="http://localhost:8000/callback", scopes=["ChannelMessage.Send", "Mail.Send"] ) notifier = Notifier(auth_config=config) auth_url = notifier.get_auth_url() print(f"Please visit: {auth_url}") # After user authorizes, exchange code for token notifier.authenticate(authorization_code="received-code")

Service Principal Authentication

Ideal for backend services and automation:

from ms365_notifier import Notifier notifier = Notifier( client_id="your-client-id", client_secret="your-client-secret", tenant_id="your-tenant-id" ) # No user interaction needed notifier.authenticate()

Delegated Authentication

Use an existing access token from another service:

from ms365_notifier import Notifier notifier = Notifier(access_token="existing-access-token") # Ready to use immediately notifier.teams.send_message(...)
Security Note: Never commit credentials to version control. Use environment variables or secure credential storage solutions.

Teams Notifications

Send rich, formatted messages to Microsoft Teams channels and users:

Basic Message

notifier.teams.send_message( channel_id="19:channel_id@thread.tacv2", message="System deployment completed successfully ✅" )

Adaptive Card

from ms365_notifier.cards import AdaptiveCard, TextBlock, ActionSet, OpenUrlAction card = AdaptiveCard( body=[ TextBlock("🚨 Production Alert", size="large", weight="bolder"), TextBlock("CPU usage exceeded 90% on server PROD-WEB-01") ], actions=[ OpenUrlAction(title="View Dashboard", url="https://monitoring.example.com") ] ) notifier.teams.send_card( channel_id="19:channel_id@thread.tacv2", card=card )

Mentions and Formatting

notifier.teams.send_message( channel_id="19:channel_id@thread.tacv2", message="john.doe@company.com Please review the latest PR", mentions=[{ "id": 0, "mentionText": "john.doe@company.com", "mentioned": { "user": { "id": "user-guid", "displayName": "John Doe" } } }] )

Outlook Integration

Send emails through Outlook with full HTML support and attachments:

notifier.outlook.send_email(recipients, subject, body, **kwargs)
Parameter Type Description Required
recipients list[str] Email addresses of recipients Required
subject str Email subject line Required
body str Email body (HTML supported) Required
cc list[str] CC recipients Optional
attachments list[Attachment] File attachments Optional
importance str Email importance: "low", "normal", "high" Optional

Example: Send HTML Email with Attachment

from ms365_notifier.outlook import Attachment # Create an attachment report = Attachment( filename="monthly_report.pdf", content=report_bytes, content_type="application/pdf" ) # Send email notifier.outlook.send_email( recipients=["manager@company.com"], cc=["team@company.com"], subject="Monthly Report - January 2024", body="""

Monthly Report

Please find attached the monthly report for January 2024.

  • Total Revenue: $125,000
  • New Customers: 45
  • Customer Satisfaction: 94%

Best regards,
Analytics Team

""", attachments=[report], importance="high" )

Error Handling

MS365 Notifier provides comprehensive error handling with specific exception types:

from ms365_notifier import Notifier from ms365_notifier.exceptions import ( AuthenticationError, RateLimitError, NotificationError, GraphAPIError ) try: notifier.teams.send_message(channel_id="...", message="Hello") except AuthenticationError as e: print(f"Authentication failed: {e}") # Refresh token or re-authenticate except RateLimitError as e: print(f"Rate limit hit. Retry after: {e.retry_after} seconds") # Implement exponential backoff except GraphAPIError as e: print(f"Graph API error: {e.status_code} - {e.message}") # Handle specific API errors except NotificationError as e: print(f"Failed to send notification: {e}") # Generic notification failure
Pro Tip: Enable debug logging to troubleshoot issues: notifier.enable_debug_logging()

Rate Limiting

MS365 Notifier automatically handles rate limiting with built-in retry logic:

# Configure rate limit handling notifier = Notifier( client_id="...", client_secret="...", tenant_id="...", rate_limit_config={ "max_retries": 3, "backoff_factor": 2, "respect_retry_after": True } )

For high-volume applications, use batch operations:

# Send multiple notifications efficiently messages = [ {"channel_id": "channel1", "message": "Update 1"}, {"channel_id": "channel2", "message": "Update 2"}, {"channel_id": "channel3", "message": "Update 3"} ] results = notifier.teams.send_batch(messages) for result in results: if result.success: print(f"Sent to {result.channel_id}") else: print(f"Failed: {result.error}")

Next Steps

Explore more features and advanced use cases:

Version: v2.3.0 | Last updated: January 2024