-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimap_connect.py
72 lines (60 loc) · 2.43 KB
/
imap_connect.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
import imaplib
import email.message
import json
import re
import secrets
from pprint import pprint
# Connect to the server
print('Connecting to ', secrets.server)
connection = imaplib.IMAP4_SSL(secrets.server, secrets.port)
# Login to our account
print('Logging in as ', secrets.username)
connection.login(secrets.username, secrets.password)
msg_number = int()
try:
typ, data = connection.list()
print('Response code:', typ)
print('Response:')
pprint(data)
typ, data = connection.select('Drafts', readonly=True)
print(typ, data)
num_msgs = int(data[0])
print('There are %d messages in Drafts' % num_msgs)
theDict = dict()
with open("test_dump.json", "w") as write_file:
# num_msgs to read all messages.
for message in range(num_msgs):
msg_number += 1
#theDict[msg_number] = list()
typ, msg_data = connection.fetch("{}".format(msg_number), '(RFC822)')
for response_part in msg_data:
if isinstance(response_part, tuple):
meta = email.message_from_string(response_part[1].decode("utf-8"))
#for header in [ 'to', 'from', 'subject' ]:
#theDict[msg_number].append(meta[header])
if str(meta.is_multipart()):
try:
# Plaintext
if meta.get_payload()[0]:
for line in str(meta.get_payload()[0]).splitlines():
if re.match('https?://+', line):
theDict[meta['subject']] = line
else:
pass
#html
elif meta.get_payload()[1]:
for line in str(meta.get_payload()[1]).splitlines():
if re.match('https?://+', line):
theDict[meta['subject']] = line
except:
theDict[meta['subject']] = None
else:
theDict[meta['subject']] = meta.get_payload(None, True)
#print(theDict[meta['subject']])
json.dump(theDict, write_file)
finally:
try:
connection.close()
except:
pass
connection.logout()