Shared folders can be skipped from config file and readonly folders are handled
[imap-fix-internaldate] / src / mail_iterator.py
CommitLineData
c9da760a
PD
1'''
2mail_iterator.py - The module contains the MailIterator class.
3
4Copyright (c) 2012 Intra2net AG
5Author: Plamen Dimitrov
6
7This program is free software: you can redistribute it and/or modify
8it under the terms of the GNU General Public License as published by
9the Free Software Foundation, either version 3 of the License, or
10(at your option) any later version.
11
12This program is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15GNU General Public License for more details.
c9da760a
PD
16'''
17
18import imaplib
19import re
20import time
8fe4e3ff 21import logging
c9da760a 22
8301e589
PD
23MAILBOX_RESP = re.compile(r'\((?P<flags>.*?)\) "(?P<delimiter>.*)" (?P<name>.*)')
24UIDVAL_RESP = re.compile(r'(?P<name>.*) \(UIDVALIDITY (?P<uidval>.*)\)')
c9da760a
PD
25
26class MailIterator:
27 """This class communicates with the e-mail server."""
c9da760a 28
7a1d4c35
PD
29 # class attributes
30 # IMAP4_SSL for connection with an IMAP server
31 mail_con = None
32 # list of tuples (uidvalidity, mailboxname) for the retrieved mailboxes
33 mailboxes = None
97bd6bea
PD
34 # logged in status
35 logged_in = None
95467f63
PD
36 # skip shared folders
37 skip_shared_folders = None
7a1d4c35 38
95467f63 39 def __init__(self, server, username, password, skip_shared_folders = False):
c9da760a 40 """Creates a connection and a user session."""
97bd6bea
PD
41 try:
42 self.mail_con = imaplib.IMAP4_SSL(server)
43 self.mail_con.login(username, password)
44 logging.info("Logged in as %s.", username)
45 except:
46 self.logged_in = False
47 raise UserWarning("Could not log in as user " + username + ".")
48 self.logged_in = True
3103ebb0
PD
49 try:
50 result, self.mailboxes = self.mail_con.list()
51 except:
c9da760a 52 raise UserWarning("Could not retrieve mailboxes for user " + username + ".")
95467f63 53 self.skip_shared_folders = skip_shared_folders
c9da760a
PD
54
55 def __del__(self):
56 """Closes the connection and the user session."""
97bd6bea 57 if(self.logged_in):
3103ebb0
PD
58 try:
59 self.mail_con.close()
60 self.mail_con.logout()
61 except:
62 pass
c9da760a
PD
63
64 def __iter__(self):
8301e589 65 """Iterates through all mailboxes, returns (uidval,name)."""
c9da760a 66 for mailbox in self.mailboxes:
8fe4e3ff 67 logging.debug("Checking mailbox %s.", mailbox)
8a9d4c89 68 mailbox = MAILBOX_RESP.match(mailbox.decode('iso-8859-1')).groups()
95467f63
PD
69 # detect if mailbox is shared and if skip flag is set iterate further
70 if(self.skip_shared_folders and mailbox[2].split(mailbox[1])[0] == '"user'):
71 logging.info("Mailbox %s is shared and therefore skipped.", mailbox[2])
72 continue
73 # retrieve uidvalidity
3103ebb0
PD
74 try:
75 result, data = self.mail_con.status(mailbox[2], '(UIDVALIDITY)')
76 except:
8301e589 77 raise UserWarning("Could not retrieve mailbox uidvalidity.")
8a9d4c89 78 uidval = UIDVAL_RESP.match(data[0].decode('iso-8859-1')).groups()
8fe4e3ff 79 logging.debug("Extracted mailbox info is %s %s.", data[0], uidval)
95467f63
PD
80 # select mailbox if writable
81 try:
82 self.mail_con.select(mailbox[2])
83 except self.mail_con.readonly:
84 logging.warning("Mailbox %s is not writable and therefore skipped.", mailbox[2])
85 continue
8301e589 86 yield (mailbox[2], uidval[1])
c9da760a
PD
87
88 def fetch_messages(self):
89 """Fetches the messages from the current mailbox, return list of uids."""
3103ebb0
PD
90 try:
91 result, data = self.mail_con.uid('search', None, "ALL")
92 except:
c9da760a 93 raise UserWarning("Could not fetch messages.")
c9da760a
PD
94 mailid_list = data[0].split()
95 return mailid_list
96
97 def fetch_internal_date(self, mid):
98 """Fetches the internal date of a message, returns a time tuple."""
3103ebb0
PD
99 try:
100 result, data = self.mail_con.uid('fetch', mid, '(INTERNALDATE)')
101 except:
67d0bfd4 102 raise UserWarning("Could not fetch the internal date of message" + mid.decode('iso-8859-1') + ".")
c9da760a
PD
103 internal_date = imaplib.Internaldate2tuple(data[0])
104 return internal_date
105
106 def fetch_received_date(self, mid):
107 """Fetches the received date of a message, returns bytes reponse."""
3103ebb0
PD
108 try:
109 result, data = self.mail_con.uid('fetch', mid, '(BODY.PEEK[HEADER.FIELDS (RECEIVED)])')
110 except:
67d0bfd4 111 raise UserWarning("Could not fetch the received header of message" + mid.decode('iso-8859-1') + ".")
8a9d4c89 112 return data[0][1].decode('iso-8859-1')
c9da760a 113
87cde111
PD
114 def fetch_basic_date(self, mid):
115 """Fetches the basic date of a message, returns bytes reponse."""
116 try:
117 result, data = self.mail_con.uid('fetch', mid, '(BODY.PEEK[HEADER.FIELDS (DATE)])')
118 except:
119 raise UserWarning("Could not fetch the date header of message" + mid.decode('iso-8859-1') + ".")
120 return data[0][1].decode('iso-8859-1')
121
c9da760a
PD
122 def update_message(self, mid, mailbox, internal_date):
123 """Replaces a message with one with correct internal date."""
124 internal_date_seconds = time.mktime(internal_date.timetuple())
125 internal_date_str = imaplib.Time2Internaldate(internal_date_seconds)
3103ebb0
PD
126 try:
127 result, data = self.mail_con.uid('fetch', mid, '(RFC822)')
128 #logging.debug("Entire e-mail is: %s", data[0][1])
c9da760a 129
3103ebb0
PD
130 fetched_flags = self.mail_con.uid('fetch', mid, '(FLAGS)')[1][0]
131 parsed_flags = imaplib.ParseFlags(fetched_flags)
132 flags_str = " ".join(flag.decode('iso-8859-1') for flag in parsed_flags)
133 result, data = self.mail_con.append(mailbox, flags_str,
134 internal_date_str, data[0][1])
135 logging.debug("Adding corrected copy of the message reponse: %s %s", result, data)
136 except:
67d0bfd4 137 raise UserWarning("Could not replace the e-mail" + mid.decode('iso-8859-1') + ".")
3103ebb0 138 try:
c9da760a 139 result, data = self.mail_con.uid('STORE', mid, '+FLAGS', r'(\Deleted)')
8fe4e3ff 140 logging.debug("Removing old copy of the message reponse: %s %s", result, data)
3103ebb0 141 except:
67d0bfd4 142 raise UserWarning("Could not delete the e-mail" + mid.decode('iso-8859-1') + ".")
3103ebb0 143 self.mail_con.expunge()
c9da760a 144 return