summaryrefslogtreecommitdiff
path: root/bin/mail-unread-count.py
blob: b9143b94461f4d4206ea80fc7f6a8e2e8a7980b3 (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
#!/usr/bin/env python2.7
"""
Config file is ~/.screen_hooks and should contain:

[email]
server = server.hostname
user = username
password = password
ssl = true or false
"""
import re
import sys
import socket
import os.path
import imaplib
import subprocess
import ConfigParser

try:
    cfg = ConfigParser.SafeConfigParser()
    cfg.readfp(open(os.path.expanduser('~/.screen_hooks')))
except IOError:
    sys.exit(0)

try:
    if cfg.getboolean('email', 'ssl'):
        imap_class = imaplib.IMAP4_SSL
        imap_port = imaplib.IMAP4_SSL_PORT
except ConfigParser.NoOptionError:
    imap_class = imaplib.IMAP4
    imap_port = imaplib.IMAP4_PORT

try:
    timeout = cfg.getint('email', 'timeout')
except ConfigParser.NoOptionError:
    timeout = 5

try:
    imap_port = cfg.getint('email', 'port')
except ConfigParser.NoOptionError:
    pass

password = cfg.get('email', 'password')
if password.startswith("`") and password.endswith("`"):
    password = subprocess.check_output(password[1:-1], shell=True).strip()

try:
    socket.setdefaulttimeout(timeout)
    conn = imap_class(cfg.get('email', 'server'), imap_port)
    conn.login(cfg.get('email', 'user'), password)

    unread = int(re.search("UNSEEN (\d+)",
            conn.status("INBOX", "(UNSEEN)")[1][0]).group(1))
except:
    unread = "#[fg=red]E"

if unread:
    print("#[fg=green][#[fg=white]{}#[fg=green]]".format(unread))