mail 4.51 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ft=python et softtabstop=4 cinoptions=4 shiftwidth=4 ts=4 ai

"""
Copyright(C) 2010  Romain Bignon

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

"""

23
24
25
26
27
from email.mime.text import MIMEText
from smtplib import SMTP
from email.Header import Header
from email.Utils import parseaddr, formataddr
import time
28
import sys
29

Romain Bignon's avatar
Romain Bignon committed
30
from weboob import Weboob
Romain Bignon's avatar
Romain Bignon committed
31
from weboob.capabilities.messages import ICapMessages
32
from weboob.tools.application import BaseApplication
33

34
class Application(BaseApplication):
Christophe Benz's avatar
Christophe Benz committed
35
    APPNAME = 'mail'
Romain Bignon's avatar
Romain Bignon committed
36
37
38
39
    CONFIG = {'interval':  15,
              'domain':    'weboob.example.org',
              'recipient': 'weboob@example.org',
              'smtp':      'localhost'}
Romain Bignon's avatar
Romain Bignon committed
40

41
    def main(self, argv):
Romain Bignon's avatar
Romain Bignon committed
42
        if not self.config:
43
44
45
46
            print >>sys.stderr, "Error: %s is not configured yet. Please call 'weboob2mail -c'" % argv[0]
            print >>sys.stderr, "Also, you need to use 'weboobcfg' to set backend configs"
            return -1

47
        self.weboob.load_modules(ICapMessages)
48

Romain Bignon's avatar
Romain Bignon committed
49
50
        self.weboob.schedule(self.config['interval'], self.process)
        self.weboob.config.save()
51
52
53
        self.weboob.loop()

    def process(self):
54
55
        for name, backend in self.weboob.iter_backends():
            for message in backend.iter_new_messages():
Christophe Benz's avatar
Christophe Benz committed
56
                self.send_email(name, message)
57

Romain Bignon's avatar
Romain Bignon committed
58
59
60
    def send_email(self, backend_name, mail):
        domain = self.config['domain']
        recipient = self.config['recipient']
61
62

        reply_id = ''
63
64
65
66
        if mail.get_reply_id():
            reply_id = u'%s.%s@%s' % (backend_name, mail.get_full_reply_id(), domain)
        subject = u'%s%s' % ((reply_id) and 'Re: ' or '', mail.get_title())
        sender = u'%s <%s.%s.%s@%s>' % (mail.get_from(), backend_name, mail.get_thread_id(), mail.get_id(), domain)
67

68
69
70
71
        # assume that get_date() returns an UTC datetime
        date = time.strftime('%a, %d %b %Y %H:%M:%S +0000', mail.get_date().timetuple())
        msg_id = u'%s.%s@%s' % (backend_name, mail.get_full_id(), domain)
        body = mail.get_content()
72

73
        if mail.get_signature():
Romain Bignon's avatar
Romain Bignon committed
74
            body += u'\n\n-- \n'
75
            body += mail.get_signature()
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119

        # Header class is smart enough to try US-ASCII, then the charset we
        # provide, then fall back to UTF-8.
        header_charset = 'ISO-8859-1'

        # We must choose the body charset manually
        for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
            try:
                body.encode(body_charset)
            except UnicodeError:
                pass
            else:
                break

        # Split real name (which is optional) and email address parts
        sender_name, sender_addr = parseaddr(sender)
        recipient_name, recipient_addr = parseaddr(recipient)

        # We must always pass Unicode strings to Header, otherwise it will
        # use RFC 2047 encoding even on plain ASCII strings.
        sender_name = str(Header(unicode(sender_name), header_charset))
        recipient_name = str(Header(unicode(recipient_name), header_charset))

        # Make sure email addresses do not contain non-ASCII characters
        sender_addr = sender_addr.encode('ascii')
        recipient_addr = recipient_addr.encode('ascii')

        # Create the message ('plain' stands for Content-Type: text/plain)
        msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
        msg['From'] = formataddr((sender_name, sender_addr))
        msg['To'] = formataddr((recipient_name, recipient_addr))
        msg['Subject'] = Header(unicode(subject), header_charset)
        msg['Message-Id'] = msg_id
        msg['Date'] = date
        if reply_id:
            msg['In-Reply-To'] = reply_id

        # Send the message via SMTP to localhost:25
        smtp = SMTP(self.config['smtp'])
        smtp.sendmail(sender, recipient, msg.as_string())
        smtp.quit()

        return msg['Message-Id']

120
121
122
if __name__ == '__main__':
    app = Application()
    sys.exit(app.main(sys.argv))