-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImapMonitor.py
162 lines (124 loc) · 5.25 KB
/
ImapMonitor.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
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
# vim: set fileencoding=utf-8 sw=4 expandtab ts=4 :
#-----------------------------------------------------------------------------
#
# Imap Monitor
#
# Copyright (C) 2018 Florian Pose
#
# This file is part of Alarm Display.
#
# Alarm Display is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Alarm Display is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# Alarm Display. If not, see <http://www.gnu.org/licenses/>.
#
#-----------------------------------------------------------------------------
import time
from imapclient import IMAPClient
import email
from PyQt5 import QtCore
#-----------------------------------------------------------------------------
class ImapMonitor(QtCore.QObject):
receivedAlarm = QtCore.pyqtSignal(bytes)
finished = QtCore.pyqtSignal()
#-----------------------------------------------------------------------------
def __init__(self, config, logger):
super(ImapMonitor, self).__init__()
self.logger = logger
self.run = True
self.imapHost = config.get('email', 'imap_host', fallback = None)
self.imapUser = config.get('email', 'imap_user', fallback = None)
self.imapPass = config.get('email', 'imap_pass', fallback = None)
self.imapCred = config.get('email', 'imap_cred', fallback = None)
if self.imapCred:
credFile = open(self.imapCred, 'r')
lines = credFile.readlines()
credFile.close()
if len(lines) != 2:
self.logger.error('Credentials file needs two lines!')
else:
if not self.imapUser:
self.imapUser = lines[0].strip()
if not self.imapPass:
self.imapPass = lines[1].strip()
if not self.imapHost or not self.imapUser or not self.imapPass:
self.run = False
#-----------------------------------------------------------------------------
def start(self):
self.logger.info(u'Started IMAP monitor.')
while self.run:
try:
self.imapCycle()
except OSError as e:
self.logger.error('IMAP cycle failed: %s', e)
except:
self.logger.error('IMAP cycle failed:', exc_info = True)
if self.run:
time.sleep(60)
self.logger.info(u'IMAP monitor finished.')
self.finished.emit()
#-----------------------------------------------------------------------------
def imapCycle(self):
self.logger.info('Connecting to %s...', repr(self.imapHost))
imap = IMAPClient(self.imapHost)
self.logger.info('Logging in...')
imap.login(self.imapUser, self.imapPass)
self.logger.info('Selecting INBOX...')
ret = imap.select_folder("INBOX")
num = ret[b'EXISTS']
self.logger.info(u'Selected mailbox with %s messages.', num)
self.logger.info(u'Starting IMAP idle mode.')
imap.idle()
while self.run:
try:
# Wait for an IDLE response
imap.idle_check(timeout = 60 * 5)
# TODO: process response and stay in idle mode
except:
self.logger.error('IMAP error:', exc_info = True)
break
imap.idle_done()
self.fetchNewMails(imap)
imap.idle()
imap.close()
imap.logout()
#-----------------------------------------------------------------------------
def fetchNewMails(self, imap):
messageIds = imap.search('UNSEEN')
if len(messageIds) == 0:
return
self.logger.info(u'Fetching messages %s...', messageIds)
messages = imap.fetch(messageIds, 'RFC822')
for messageId in messageIds:
imapMessage = messages[messageId]
try:
imap.set_flags(messageId, '\\Seen')
self.logger.info(u'Marked message as seen.')
except:
self.logger.error(u'Failed to mark message as seen:',
exc_info = True)
content = imapMessage[b'RFC822']
msg = email.message_from_bytes(content)
if 'From' in msg:
self.logger.info(u'From: %s', msg['From'])
if 'subject' in msg:
self.logger.info(u'Subject: %s', msg['subject'])
for part in msg.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
fileName = part.get_filename()
if fileName is None or not fileName.endswith('xml'):
continue
xmlContent = part.get_payload(decode = True)
self.receivedAlarm.emit(xmlContent)
#-----------------------------------------------------------------------------