2 mail_iterator.py - The module contains the MailIterator class.
4 Copyright (c) 2012 Intra2net AG
5 Author: Plamen Dimitrov
7 This program is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
23 MAILBOX_RESP = re.compile(r'\((?P<flags>.*?)\) "(?P<delimiter>.*)" (?P<name>.*)')
24 UIDVAL_RESP = re.compile(r'(?P<name>.*) \(UIDVALIDITY (?P<uidval>.*)\)')
27 """This class communicates with the e-mail server."""
30 # IMAP4_SSL for connection with an IMAP server
32 # list of tuples (uidvalidity, mailboxname) for the retrieved mailboxes
35 def __init__(self, server, username, password):
36 """Creates a connection and a user session."""
37 self.mail_con = imaplib.IMAP4_SSL(server)
38 result, data = self.mail_con.login(username, password)
40 raise UserWarning("Could not log in as user " + username + ". " + data)
41 result, self.mailboxes = self.mail_con.list()
43 raise UserWarning("Could not retrieve mailboxes for user " + username + ".")
46 """Closes the connection and the user session."""
48 self.mail_con.logout()
51 """Iterates through all mailboxes, returns (uidval,name)."""
52 for mailbox in self.mailboxes:
53 logging.debug("Checking mailbox %s.", mailbox)
54 mailbox = MAILBOX_RESP.match(mailbox.decode('iso-8859-1')).groups()
55 result, data = self.mail_con.status(mailbox[2], '(UIDVALIDITY)')
57 raise UserWarning("Could not retrieve mailbox uidvalidity.")
58 uidval = UIDVAL_RESP.match(data[0].decode('iso-8859-1')).groups()
59 logging.debug("Extracted mailbox info is %s %s.", data[0], uidval)
60 self.mail_con.select(mailbox[2])
61 yield (mailbox[2], uidval[1])
63 def fetch_messages(self):
64 """Fetches the messages from the current mailbox, return list of uids."""
65 result, data = self.mail_con.uid('search', None, "ALL")
67 raise UserWarning("Could not fetch messages.")
68 mailid_list = data[0].split()
71 def fetch_internal_date(self, mid):
72 """Fetches the internal date of a message, returns a time tuple."""
73 result, data = self.mail_con.uid('fetch', mid, '(INTERNALDATE)')
75 raise UserWarning("Could not fetch the internal date of message" + mid + ".")
76 internal_date = imaplib.Internaldate2tuple(data[0])
79 def fetch_received_date(self, mid):
80 """Fetches the received date of a message, returns bytes reponse."""
81 result, data = self.mail_con.uid('fetch', mid, '(BODY.PEEK[HEADER.FIELDS (RECEIVED)])')
83 raise UserWarning("Could not fetch the received header of message" + mid + ".")
84 return data[0][1].decode('iso-8859-1')
86 def update_message(self, mid, mailbox, internal_date):
87 """Replaces a message with one with correct internal date."""
88 internal_date_seconds = time.mktime(internal_date.timetuple())
89 internal_date_str = imaplib.Time2Internaldate(internal_date_seconds)
90 result, data = self.mail_con.uid('fetch', mid, '(RFC822)')
92 raise UserWarning("Could not retrieve the entire e-mail" + mid + ".")
93 #logging.debug("Entire e-mail is: %s", data[0][1])
95 fetched_flags = self.mail_con.uid('fetch', mid, '(FLAGS)')[1][0]
96 parsed_flags = imaplib.ParseFlags(fetched_flags)
97 flags_str = " ".join(flag.decode('iso-8859-1') for flag in parsed_flags)
98 result, data = self.mail_con.append(mailbox, flags_str,
99 internal_date_str, data[0][1])
100 logging.debug("Adding corrected copy of the message reponse: %s %s", result, data)
102 raise UserWarning("Could not replace the e-mail" + mid + ".")
104 result, data = self.mail_con.uid('STORE', mid, '+FLAGS', r'(\Deleted)')
105 logging.debug("Removing old copy of the message reponse: %s %s", result, data)
107 raise UserWarning("Could not delete the e-mail" + mid + ".")
108 else: self.mail_con.expunge()