1
0
Fork 1
mirror of https://github.com/coddingtonbear/django-mailbox.git synced 2026-07-09 22:38:19 +02:00
django-mailbox/django_mailbox2/transports/imap.py

136 lines
4.4 KiB
Python
Raw Normal View History

import imaplib
import logging
from django.conf import settings
from .base import EmailTransport, MessageParseError
2013-06-22 14:35:47 -07:00
# By default, imaplib will raise an exception if it encounters more
# than 10k bytes; sometimes users attempt to consume mailboxes that
# have a more, and modern computers are skookum-enough to handle just
# a *few* more messages without causing any sort of problem.
imaplib._MAXLINE = 1000000
logger = logging.getLogger(__name__)
class ImapTransport(EmailTransport):
def __init__(
2021-02-03 23:05:48 -05:00
self,
hostname,
port=None,
ssl=False,
tls=False,
archive="",
folder=None,
):
2014-05-30 16:32:57 -07:00
self.max_message_size = getattr(
2021-02-03 23:05:48 -05:00
settings, "DJANGO_MAILBOX_MAX_MESSAGE_SIZE", False
)
self.integration_testing_subject = getattr(
2021-02-03 23:05:48 -05:00
settings, "DJANGO_MAILBOX_INTEGRATION_TESTING_SUBJECT", None
)
2021-02-01 12:08:09 -05:00
self.delete_message_from_server = getattr(
2021-02-03 23:05:48 -05:00
settings, "DJANGO_MAILBOX_DELETE_MESSAGE_FROM_SERVER", True
2021-02-01 12:08:09 -05:00
)
self.hostname = hostname
self.port = port
self.archive = archive
2015-03-16 16:55:12 +03:00
self.folder = folder
self.tls = tls
if ssl:
self.transport = imaplib.IMAP4_SSL
if not self.port:
self.port = 993
else:
self.transport = imaplib.IMAP4
if not self.port:
self.port = 143
def connect(self, username, password):
self.server = self.transport(self.hostname, self.port)
if self.tls:
self.server.starttls()
typ, msg = self.server.login(username, password)
2015-03-16 16:55:12 +03:00
if self.folder:
self.server.select(self.folder)
else:
self.server.select()
def _get_all_message_ids(self):
# Fetch all the message uids
2021-02-03 23:05:48 -05:00
response, message_ids = self.server.uid("search", None, "ALL")
message_id_string = message_ids[0].strip()
# Usually `message_id_string` will be a list of space-separated
# ids; we must make sure that it isn't an empty string before
# splitting into individual UIDs.
if message_id_string:
2021-02-03 23:05:48 -05:00
return message_id_string.decode().split(" ")
return []
def _get_small_message_ids(self, message_ids):
# Using existing message uids, get the sizes and
# return only those that are under the size
# limit
safe_message_ids = []
2021-02-03 23:05:48 -05:00
status, data = self.server.uid("fetch", ",".join(message_ids), "(RFC822.SIZE)")
for each_msg in data:
each_msg = each_msg.decode()
try:
2021-02-03 23:05:48 -05:00
uid = each_msg.split(" ")[2]
size = each_msg.split(" ")[4].rstrip(")")
2014-05-30 16:32:57 -07:00
if int(size) <= int(self.max_message_size):
safe_message_ids.append(uid)
except ValueError as e:
2021-02-03 23:05:48 -05:00
logger.warning("ValueError: {} working on {}".format(e, each_msg[0]))
pass
return safe_message_ids
def get_message(self, condition=None):
message_ids = self._get_all_message_ids()
if not message_ids:
return
# Limit the uids to the small ones if we care about that
2014-05-30 16:32:57 -07:00
if self.max_message_size:
message_ids = self._get_small_message_ids(message_ids)
if self.archive:
typ, folders = self.server.list(pattern=self.archive)
if folders[0] is None:
# If the archive folder does not exist, create it
self.server.create(self.archive)
for uid in message_ids:
try:
2021-02-03 23:05:48 -05:00
typ, msg_contents = self.server.uid("fetch", uid, "(RFC822)")
2015-04-12 12:21:48 -07:00
if not msg_contents:
continue
try:
message = self.get_email_from_bytes(msg_contents[0][1])
except TypeError:
# This happens if another thread/process deletes the
# message between our generating the ID list and our
# processing it here.
continue
if condition and not condition(message):
continue
yield message
except MessageParseError:
continue
if self.archive:
2021-02-03 23:05:48 -05:00
self.server.uid("copy", uid, self.archive)
if self.delete_message_from_server:
self.server.uid("store", uid, "+FLAGS", "(\\Deleted)")
self.server.expunge()
return