scripts/imap_connect.py
author Xavier Algarra <xavier@pep-project.org>
Tue, 06 Jun 2017 07:49:23 +0200
changeset 2248 75013a586bfd
parent 1902 7eb8073f95bc
child 2998 4ca808081422
permissions -rw-r--r--
IOS-137 add multiple accounts option with the new login
dirk@742
     1
import imaplib
dirk@742
     2
import configparser
dirk@742
     3
import os
dirk@742
     4
import pprint
dirk@1901
     5
import re
dirk@742
     6
dirk@1559
     7
verboseLogging = False
dirk@1559
     8
dirk@1559
     9
def open_connection():
dirk@742
    10
    # Read the config file
dirk@742
    11
    config = configparser.ConfigParser()
dirk@742
    12
    config.read([os.path.expanduser('config.ini')])
dirk@742
    13
dirk@742
    14
    # Connect to the server
dirk@742
    15
    hostname = config.get('server', 'hostname')
dirk@1559
    16
    if verboseLogging: print('Connecting to', hostname)
dirk@742
    17
    connection = imaplib.IMAP4_SSL(hostname)
dirk@742
    18
dirk@742
    19
    # Login to our account
dirk@742
    20
    username = config.get('account', 'username')
dirk@742
    21
    password = config.get('account', 'password')
dirk@1559
    22
    if verboseLogging: print('Logging in as', username)
dirk@742
    23
    connection.login(username, password)
dirk@742
    24
    return connection
dirk@742
    25
dirk@1559
    26
def dump_folders(c):
dirk@1559
    27
    typ, data = c.list()
dirk@1559
    28
    if verboseLogging: print('Response code:', typ)
dirk@1559
    29
    pprint.pprint(data)
dirk@1559
    30
dirk@1559
    31
def dump_folder(c, folderName):
dirk@1639
    32
    print(folderName)
dirk@1559
    33
    c.select(mailbox=folderName, readonly=True)
dirk@1559
    34
    messages = c.fetch('1:*', '(UID INTERNALDATE FLAGS)')
dirk@1559
    35
    pprint.pprint(messages)
dirk@1559
    36
dirk@1901
    37
def rm_folders(c):
dirk@1901
    38
    typ, data = c.list()
dirk@1901
    39
    pprint.pprint(data)
dirk@1901
    40
    p1 = re.compile('"([^"]*)"')
dirk@1901
    41
    p2 = re.compile('INBOX.Folder')
dirk@1902
    42
    p3 = re.compile('<[a-zA-Z].*>')
dirk@1901
    43
    for line in data:
dirk@1901
    44
        m = p1.findall(str(line))
dirk@1901
    45
        if m != None:
dirk@1901
    46
            mailbox = m[1]
dirk@1902
    47
            if p2.match(mailbox) or p3.match(mailbox):
dirk@1901
    48
                print("will delete |" + mailbox + "|")
dirk@1901
    49
                quoted = '"' + mailbox + '"'
dirk@1901
    50
                r = c.delete(quoted)
dirk@1901
    51
                pprint.pprint(r)
dirk@1901
    52
dirk@742
    53
if __name__ == '__main__':
dirk@1559
    54
    c = open_connection()
dirk@742
    55
    try:
dirk@742
    56
        print(c)
dirk@1559
    57
        dump_folder(c, 'INBOX')
dirk@1639
    58
        dump_folder(c, 'INBOX.Trash')
dirk@1901
    59
        rm_folders(c)
dirk@742
    60
    finally:
dirk@742
    61
        c.logout()