summaryrefslogtreecommitdiff
path: root/new-mail-notify
blob: 92f8bcf149810489df8c6206c24353033767fc64 (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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from email.header import decode_header
from os import execlp
from xml.sax.saxutils import escape
import email
import mailbox
import sys
import re

INBOX_DIR = '~/Mail/Gmail/INBOX'
N_ICON = '~/.icons/email.svg'
N_TIME = 15 * 1000 # 15 seconds
MAX_DETAIL = 6

def decode(string, charset = 'utf8'):
    return ' '.join(d[0].decode(d[1] or charset) for d in decode_header(string))

def notify(messages):
    if len(messages) == 0:
        sys.exit(0)
    title = "Новая почта (%d)" % len(messages)
    m = []
    for message in messages[:MAX_DETAIL]:
        detail  = '<b>' + escape(message['Subject']) + '</b>\n'
        detail += '<i>' + escape(message['From']) + '</i>'
        m.append(detail)
    details = '\n\n'.join(m)
    details += '\n'
    execlp('notify-send', 'notify-send', '-t', str(N_TIME), '-i', N_ICON, title, details)

def get_messages(inbox):
    box = mailbox.Maildir(inbox, factory=None)
    msgs = []
    for key in sorted(box.iterkeys(), reverse=True):
        try:
            message = box[key]
        except email.Errors.MessageParseError:
            continue
        if 'S' in message.get_flags():
            continue

        msgs += [{ 
            'From': decode(message.get('From')),
            'Subject': decode(message.get('Subject'))
        },]
    return msgs

if __name__ == '__main__':
    notify(get_messages(INBOX_DIR))