-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfastmail.py
98 lines (92 loc) · 3.74 KB
/
fastmail.py
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
import json
from os import getenv
import requests
class Fastmail:
def __init__(self):
self.token = getenv('FASTMAIL_TOKEN')
self.endpoint = 'https://api.fastmail.com/jmap'
self.headers = {
'Authorization': f'Bearer {self.token}',
'Content-Type': 'application/json',
}
self.account_id = self.get_account()
def get_account(self):
response = requests.get(url=f'{self.endpoint}/session',
headers=self.headers)
return response.json()['primaryAccounts']['urn:ietf:params:jmap:core']
def test_request(self):
data = {
'using': ['urn:ietf:params:jmap:core', 'urn:ietf:params:jmap:mail'],
'methodCalls': [
['Core/echo', {
'accountId': self.account_id,
'hello': True,
'blarg': 5
},
'a']
]}
response = requests.post(url=f'{self.endpoint}/api',
headers=self.headers,
data=json.dumps(data))
print(response)
print(response.text)
return response.json()
def get_mail_body_ids(self):
data = {
'using': ['urn:ietf:params:jmap:core', 'urn:ietf:params:jmap:mail'],
'methodCalls': [
['Email/query', {
'accountId': self.account_id,
'filter': {
'operator': 'OR',
'conditions': [
{'subject': getenv('MAIL_SUBJECT_ELECTRIC')},
{'subject': getenv('MAIL_SUBJECT_GAS')}]},
'sort': [{"property": "receivedAt", "isAscending": False}],
'limit': 2, # We only need the latest copy of each bill
'calculateTotal': True
},
't0'],
['Email/get', {
'accountId': self.account_id,
'#ids': {
'resultOf': 't0',
'name': 'Email/query',
'path': '/ids'
},
'properties': ['threadId']
},
't1'],
['Thread/get', {
'accountId': self.account_id,
'#ids': {
'resultOf': 't1',
'name': 'Email/get',
'path': '/list/*/threadId'
},
}, 't2'],
['Email/get', {
'accountId': self.account_id,
'#ids': {
'resultOf': 't2',
'name': 'Thread/get',
'path': '/list/*/emailIds'
},
# 'properties': ['from', 'receivedAt', 'subject']
}, 't3']
]
}
response = requests.post(url=f'{self.endpoint}/api',
headers=self.headers,
data=json.dumps(data))
# print(response.text)
# print(response.json()['methodResponses'][3][1]['list'][0]['htmlBody'][0]['blobId'])
blob_ids = [mail['htmlBody'][0]['blobId'] for mail in response.json()['methodResponses'][3][1]['list']]
return blob_ids
def get_mail(self, blob_ids):
for blob in blob_ids:
endpoint = f'https://www.fastmailusercontent.com/jmap/download/{self.account_id}/{blob}/{blob}.html?type=text/html'
response = requests.get(url=endpoint,
headers=self.headers)
with open(f'{blob}.html', 'w') as f:
f.write(response.text)