Returns the mail message with the given index. Each message is a dictionary with date, from, subject, body, attachments entries. The attachments entry is a list of (MIME-type, str)-tuples.
(self, i, attachments=False, cached=True)
| 229 | return self.__getitem__(i, attachments, cached) |
| 230 | |
| 231 | def __getitem__(self, i, attachments=False, cached=True): |
| 232 | """ Returns the mail message with the given index. |
| 233 | Each message is a dictionary with date, from, subject, body, attachments entries. |
| 234 | The attachments entry is a list of (MIME-type, str)-tuples. |
| 235 | """ |
| 236 | i += 1 |
| 237 | id = "mail-%s-%s-%s-%s" % (self.parent._id, self.name, i, attachments) |
| 238 | if cached and id in cache: |
| 239 | m = cache[id] |
| 240 | else: |
| 241 | # Select the current mail folder. |
| 242 | # Get the e-mail header. |
| 243 | # Get the e-mail body, with or without file attachments. |
| 244 | status, response = self.parent.imap4.select(self._name, readonly=1) |
| 245 | status, response1 = self.parent.imap4.fetch(str(i), '(BODY.PEEK[HEADER])') |
| 246 | status, response2 = self.parent.imap4.fetch(str(i), '(BODY.PEEK[%s])' % (not attachments and "TEXT" or "")) |
| 247 | time.sleep(0.1) |
| 248 | m = response1[0][1] + response2[0][1] |
| 249 | # Cache the raw message for faster retrieval. |
| 250 | if cached: |
| 251 | cache[id] = m |
| 252 | # Parse the raw message. |
| 253 | m = email.message_from_string(encode_utf8(m)) |
| 254 | d = Message([ |
| 255 | (DATE, _decode(m.get(DATE), m)), |
| 256 | (FROM, _decode(m.get(FROM), m)), |
| 257 | (SUBJECT, _decode(m.get(SUBJECT), m)), |
| 258 | (BODY, ""), |
| 259 | (ATTACHMENTS, [])]) |
| 260 | # Message body can be a list of parts, including file attachments. |
| 261 | for p in (m.is_multipart() and m.get_payload() or [m]): |
| 262 | if p.get_content_type() == "text/plain": |
| 263 | d[BODY] += _decode(p.get_payload(decode=True), p) |
| 264 | elif attachments: |
| 265 | d[ATTACHMENTS].append((p.get_content_type(), p.get_payload())) |
| 266 | for k in d: |
| 267 | if isinstance(d[k], basestring): |
| 268 | d[k] = d[k].strip() |
| 269 | d[k] = d[k].replace("\r\n", "\n") |
| 270 | return d |
| 271 | |
| 272 | def __iter__(self): |
| 273 | """ Returns an iterator over all the messages in the folder, latest-first. |