summaryrefslogtreecommitdiffstats
path: root/.bin/get-mailbox-imap
blob: b78752d6e90557271735809c29ad3e5b7b0b05da (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env python3

import imaplib
import sys


def get_boxes(list):
    """ Retrieve and decode all mailboxes. """
    return [box.decode('utf-8').rsplit(' ')[-1] for box in list]


def flatten_output(list):
    """ Print all boxes with a flattened output. """
    return ''.join([f"+'{box}' " for box in list])


def sort_mailboxes(mailboxes):
    """ Sort boxes list according to a predefined order. """

    order = [
        "INBOX",
        "Unread",
        "Drafts",
        "Sent",
        "Spam",
        "Trash",
        "Junk",
        "Archive"
    ]

    mailboxes = sorted(mailboxes)

    # sort based on predefined order
    output = []
    for exp in order:
        matching = [s for s in mailboxes if exp in s]
        output.extend(matching)

    # ensure all retrieved boxes are present
    for box in mailboxes:
        if box not in output:
            output.append(box)

    return output


def main():
    """
    Retrieve, sort, and pretty print for neomutt
    """

    # user information
    remote = sys.argv[1]
    username = sys.argv[2]
    password = sys.argv[3]

    # connection
    mail = imaplib.IMAP4_SSL(remote)
    mail.login(username, password)

    # parse folders output
    bxs = sort_mailboxes(get_boxes(mail.list()[1]))

    # oneline pretty-print for neomutt
    print(flatten_output(bxs), end=' ')


if __name__ == "__main__":
    main()
remember that computers suck.