-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoutlook_auth.py
More file actions
209 lines (182 loc) · 6.88 KB
/
outlook_auth.py
File metadata and controls
209 lines (182 loc) · 6.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import requests
import urllib.parse
import json
import logging
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def get_headers(additional_headers: dict = None) -> dict:
default_headers = {
'accept': 'application/json',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.9',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
}
if additional_headers:
default_headers.update(additional_headers)
return default_headers
def authenticate_username_password(email: str, password: str, proxies: dict = None) -> str:
"""
Authenticate with Microsoft and return a refresh token.
"""
client_id = "9e5f94bc-e8a4-4e73-b8be-63364c29d753"
redirect_uri = "https://localhost"
scope = "offline_access https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/MailboxSettings.ReadWrite"
try:
# Step 1: Get authorization page
auth_url = f"https://login.microsoftonline.com/common/oauth2/v2.0/authorize?" + urllib.parse.urlencode({
'client_id': client_id,
'response_type': 'code',
'redirect_uri': redirect_uri,
'scope': scope,
'login_hint': email
})
headers = get_headers()
session = requests.Session()
session.proxies = proxies if proxies else {}
# Step 2: Initial request to get cookies and form data
response = session.get(auth_url, headers=headers, allow_redirects=True)
response.raise_for_status()
# Step 3: Prepare login data
login_data = {
'login': email,
'loginfmt': email,
'passwd': password,
'type': '11',
'LoginOptions': '1'
}
# Step 4: Post login credentials
login_response = session.post(
response.url,
data=login_data,
headers=get_headers({'content-type': 'application/x-www-form-urlencoded'}),
allow_redirects=False
)
# Step 5: Follow redirects to get authorization code
redirect_url = login_response.headers.get('Location')
if not redirect_url:
logger.error("No redirect URL found in login response")
return None
# Step 6: Extract code from final redirect
code_response = session.get(redirect_url, headers=headers, allow_redirects=True)
if 'code=' not in code_response.url:
logger.error("No authorization code found in redirect URL")
return None
auth_code = urllib.parse.parse_qs(urllib.parse.urlparse(code_response.url).query).get('code')
if not auth_code:
logger.error("Failed to extract authorization code")
return None
auth_code = auth_code[0]
# Step 7: Exchange code for tokens
token_data = {
'client_id': client_id,
'code': auth_code,
'redirect_uri': redirect_uri,
'grant_type': 'authorization_code',
'scope': scope
}
token_response = session.post(
"https://login.microsoftonline.com/common/oauth2/v2.0/token",
data=token_data,
headers=get_headers({'content-type': 'application/x-www-form-urlencoded'}),
)
token_response.raise_for_status()
token_json = token_response.json()
refresh_token = token_json.get('refresh_token')
if not refresh_token:
logger.error("No refresh token in response: %s", token_json)
return None
return refresh_token
except requests.RequestException as e:
logger.error("Authentication failed: %s", str(e))
return None
def get_access_token_from_refresh(refresh_token: str, proxies: dict = None) -> str:
"""
Get access token using refresh token.
"""
token_url = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
client_id = "9e5f94bc-e8a4-4e73-b8be-63364c29d753"
redirect_uri = "https://localhost"
scope = "https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/MailboxSettings.ReadWrite"
data = {
'client_id': client_id,
'scope': scope,
'refresh_token': refresh_token,
'grant_type': 'refresh_token',
'redirect_uri': redirect_uri
}
try:
response = requests.post(
token_url,
data=data,
headers=get_headers({'content-type': 'application/x-www-form-urlencoded'}),
proxies=proxies
)
response.raise_for_status()
return response.json().get("access_token")
except requests.RequestException as e:
logger.error("Failed to get access token: %s", str(e))
return None
def create_forwarding_rule(token: str, forward_to: str, proxies: dict = None) -> str:
"""
Create a mail forwarding rule using Microsoft Graph API.
"""
url = "https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messageRules"
headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
rule_data = {
"displayName": f"Forward to {forward_to}",
"sequence": 1,
"isEnabled": True,
"conditions": {
"senderContains": [
"popmart",
"nike",
"pokemon",
"target",
"walmart",
"amazon",
"shopify",
"bestbuy",
"uber",
"goat"
]
},
"actions": {
"forwardTo": [
{
"emailAddress": {
"address": forward_to
}
}
],
"stopProcessingRules": True
}
}
try:
response = requests.post(url, json=rule_data, headers=headers, proxies=proxies)
response.raise_for_status()
logger.info("Mail forwarding rule created successfully")
return ""
except requests.RequestException as e:
error_msg = f"Error creating rule: {str(e)}"
logger.error(error_msg)
return error_msg
if __name__ == "__main__":
# Example usage
email = "example@outlook.com"
password = "your_password"
forward_to = "forward@example.com"
proxies = None # Or set to {'http': 'proxy_url', 'https': 'proxy_url'}
refresh_token = authenticate_username_password(email, password, proxies)
if refresh_token:
access_token = get_access_token_from_refresh(refresh_token, proxies)
if access_token:
result = create_forwarding_rule(access_token, forward_to, proxies)
print(result or "Success!")
else:
print("Failed to get access token")
else:
print("Authentication failed")