81 lines
2.4 KiB
Python
Executable File
81 lines
2.4 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""
|
|
Microsoft Graph API Email Sender - ROPC Flow
|
|
Utilise les credentials utilisateur directement (bypass MFA si pas activé)
|
|
"""
|
|
|
|
import requests
|
|
import sys
|
|
import json
|
|
|
|
def get_token_ropc(tenant_id, client_id, username, password):
|
|
"""Get token using Resource Owner Password Credentials"""
|
|
url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
|
|
|
|
data = {
|
|
'grant_type': 'password',
|
|
'client_id': client_id,
|
|
'username': username,
|
|
'password': password,
|
|
'scope': 'https://graph.microsoft.com/Mail.Send'
|
|
}
|
|
|
|
response = requests.post(url, data=data)
|
|
if response.status_code == 200:
|
|
return response.json().get('access_token'), None
|
|
else:
|
|
return None, response.json()
|
|
|
|
def send_email(token, from_email, to_email, subject, body):
|
|
"""Send email via Graph API"""
|
|
url = f"https://graph.microsoft.com/v1.0/me/sendMail"
|
|
|
|
headers = {
|
|
'Authorization': f'Bearer {token}',
|
|
'Content-Type': 'application/json'
|
|
}
|
|
|
|
email_data = {
|
|
"message": {
|
|
"subject": subject,
|
|
"body": {"contentType": "Text", "content": body},
|
|
"toRecipients": [{"emailAddress": {"address": to_email}}]
|
|
},
|
|
"saveToSentItems": "false"
|
|
}
|
|
|
|
response = requests.post(url, headers=headers, json=email_data)
|
|
return response.status_code == 202, response.text
|
|
|
|
def main():
|
|
if len(sys.argv) < 6:
|
|
print("Usage: graph-sender-ropc.py <tenant_id> <client_id> <username> <password> <to> <subject> [body]")
|
|
sys.exit(1)
|
|
|
|
tenant_id = sys.argv[1]
|
|
client_id = sys.argv[2]
|
|
username = sys.argv[3]
|
|
password = sys.argv[4]
|
|
to_email = sys.argv[5]
|
|
subject = sys.argv[6] if len(sys.argv) > 6 else "Hello"
|
|
body = sys.argv[7] if len(sys.argv) > 7 else "Test email"
|
|
|
|
token, error = get_token_ropc(tenant_id, client_id, username, password)
|
|
|
|
if not token:
|
|
error_code = error.get('error', 'unknown')
|
|
error_desc = error.get('error_description', '')[:100]
|
|
print(f"TOKEN_ERROR:{error_code}:{error_desc}")
|
|
sys.exit(1)
|
|
|
|
success, result = send_email(token, username, to_email, subject, body)
|
|
|
|
if success:
|
|
print("OK")
|
|
else:
|
|
print(f"SEND_ERROR:{result[:200]}")
|
|
sys.exit(1)
|
|
|
|
if __name__ == "__main__":
|
|
main()
|