'Fetches emails'

def get_emails(self):

    if ((self.incoming_server_type == 'IMAP') or (self.incoming_server_type == 'IMAP-SSL')):
        HARDTREE_MESSAGING_IMAP_LIMIT = getattr(settings, 'HARDTREE_MESSAGING_IMAP_LIMIT', 100)
        (port, ssl) = self.get_imap_port()
        if ssl:
            M = imaplib.IMAP4_SSL(self.incoming_server_name, port)
        else:
            M = imaplib.IMAP4(self.incoming_server_name, port)
        M.login(self.incoming_server_username, self.incoming_password)
        M.select()
        msgnums = []
        try:
            (typ, data) = M.sort('REVERSE    DATE', 'UTF-8', self.folder_name)
            msgnums = (data[0].split() if data[0] else [])
        except:
            (typ, data) = M.search(None, self.folder_name)
            msgnums = (data[0].split() if data[0] else [])
            msgnums = sorted(msgnums, cmp=intcmp, reverse=True)
        for num in msgnums[:HARDTREE_MESSAGING_IMAP_LIMIT]:
            (resp, msg) = M.fetch(num, '(RFC822)')
            mail = email.message_from_string(msg[0][1])
            self.process_mail(mail)
            if (self.folder_name == 'UNSEEN'):
                M.store(num, '+FLAGS', '\\Seen')
        M.close()
        M.logout()
    if ((self.incoming_server_type == 'POP3') or (self.incoming_server_type == 'POP3-SSL')):
        HARDTREE_MESSAGING_POP3_LIMIT = getattr(settings, 'HARDTREE_MESSAGING_POP3_LIMIT', 100)
        (port, ssl) = self.get_pop_port()
        if ssl:
            M = poplib.POP3_SSL(self.incoming_server_name, port)
        else:
            M = poplib.POP3(self.incoming_server_name, port)
        M.user(self.incoming_server_username)
        M.pass_(self.incoming_password)
        numMessages = len(M.list()[1])
        if (numMessages >= HARDTREE_MESSAGING_POP3_LIMIT):
            limit = (numMessages - HARDTREE_MESSAGING_POP3_LIMIT)
        else:
            limit = 0
        for i in range(limit, numMessages):
            lines = M.retr(i)[1]
            mail = email.message_from_string('\n'.join(lines))
            self.process_mail(mail)
        M.quit()
