aboutsummaryrefslogtreecommitdiffstats
path: root/climl_imap_bridge.py
blob: c0ddb82e6f11977ebe44c8513afb5b104831f656 (plain)
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
#!/usr/bin/python3

import os
import subprocess
import confparser
import imapclient

import backports.ssl

def conf_boolean_postprocess(src):
    src = src.lower().strip()
    if src == 'true' or src == 'on' or src == '1':
        return True
    return False

def conf_postprocess(conf):
    d = {
            'imap.tls':                     conf_boolean_postprocess,
            'imap.start_tls':               conf_boolean_postprocess,
            'imap.tls_nocheck_hostname':    conf_boolean_postprocess,
            'imap.tls_nocheck_ca':          conf_boolean_postprocess,
    }
    return {key: d[key](value) if key in d else value
            for key, value in conf.items()}

def connect_to_imap(conf, password):

    cafile = conf.get('imap.tls_ca', None)

    if cafile:
        cafile = os.path.expanduser(cafile)

    ssl_context = imapclient.create_default_context(cafile=cafile)

    if conf.get('imap.tls_nocheck_hostname', False):
        # don't check if certificate hostname doesn't match target hostname
        ssl_context.check_hostname = False

    if conf.get('imap.tls_nocheck_ca', False):
        # don't check if the certificate is trusted by a certificate authority
        ssl_context.verify_mode = backports.ssl.CERT_NONE

    connection = imapclient.IMAPClient(host=conf.get('imap.server'),
            ssl=conf.get('imap.tls', True),
            ssl_context=ssl_context)
    if conf.get('imap.start_tls', False):
        connection.start_tls(ssl_context=ssl_context)
    print('connection succeed')
    connection.login(username=conf.get('imap.username'), password=password)
    print('successfuly logged')
    return connection

def main():
    confpath = os.path.expanduser('~/temp/conf.cfg')
    conf = conf_postprocess(confparser.read_conf(confpath))
    print('Read conf:', conf)
    password_command = conf.get('imap.password_command', None)
    if password_command:
        password = subprocess.check_output(password_command, shell=True)
        password = password.rstrip().decode('utf8')
        print('got pasword:', password)
    connection = connect_to_imap(conf, password)



main() # dev mode for now