source: emailtotracscript/trunk/email2trac.py.in @ 41

Last change on this file since 41 was 41, checked in by bas, 18 years ago

EmailtoTracScript?:

email2trac.py.in:

  • Added TicketNotify? function (Kilian Cavalotti)
  • Unified importing of python trac modules
  • Revert changes to Spam control. It works as it used to be.


  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 15.0 KB
Line 
1#!@PYTHON@
2# Copyright (C) 2002
3#
4# This file is part of the email2trac utils
5#
6# This program is free software; you can redistribute it and/or modify it
7# under the terms of the GNU General Public License as published by the
8# Free Software Foundation; either version 2, or (at your option) any
9# later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
19#
20"""
21emailfilter.py -- Email tickets to Trac.
22
23A simple MTA filter to create Trac tickets from inbound emails.
24
25Copyright 2005, Daniel Lundin <daniel@edgewall.com>
26Copyright 2005, Edgewall Software
27
28Changed By: Bas van der Vlies <basv@sara.nl>
29Date      : 13 September 2005
30Descr.    : Added config file and command line options, spam level
31            detection, reply address and mailto option. Unicode support
32
33Changed By: Walter de Jong <walter@sara.nl>
34Descr.    : multipart-message code and trac attachments
35
36
37The scripts reads emails from stdin and inserts directly into a Trac database.
38MIME headers are mapped as follows:
39
40        * From:      => Reporter
41                     => CC (Optional via reply_address option)
42        * Subject:   => Summary
43        * Body       => Description
44        * Component  => Can be set to SPAM via spam_level option
45
46How to use
47----------
48 * Create an config file:
49        [DEFAULT]                        # REQUIRED
50        project      : /data/trac/test   # REQUIRED
51        debug        : 1                 # OPTIONAL, if set print some DEBUG info
52        spam_level   : 4                 # OPTIONAL, if set check for SPAM mail
53        reply_address: 1                 # OPTIONAL, if set then fill in ticket CC field
54        umask        : 022               # OPTIONAL, if set then use this umask for creation of the attachments
55        mailto_link  : 1                 # OPTIONAL, if set then [mailto:<CC>] in description
56        trac_version : 0.8               # OPTIONAL, default is 0.9
57
58        [jouvin]                         # OPTIONAL project declaration, if set both fields necessary
59        project      : /data/trac/jouvin # use -p|--project jouvin. 
60       
61 * default config file is : /etc/email2trac.conf
62
63 * Commandline opions:
64                -h | --help
65                -c <value> | --component=<value>
66                -f <config file> | --file=<config file>
67                -p <project name> | --project=<project name>
68
69SVN Info:
70        $Id: email2trac.py.in 41 2006-01-25 14:20:10Z bas $
71"""
72
73import os
74import sys
75import string
76import getopt
77import stat
78import time
79import email
80import re
81import urllib
82import unicodedata
83import ConfigParser
84from email import Header
85from stat import *
86import mimetypes
87
88trac_default_version = 0.9
89
90class TicketEmailParser(object):
91        env = None
92        comment = '> '
93   
94        def __init__(self, env, parameters, version):
95                self.env = env
96
97                # Database connection
98                #
99                self.db = None
100
101                self.VERSION = version
102                if self.VERSION > 0.8:
103                        self.get_config = self.env.config.get
104                else:
105                        self.get_config = self.env.get_config
106
107                if parameters.has_key('umask'):
108                        os.umask(int(parameters['umask'], 8))
109
110                if parameters.has_key('debug'):
111                        self.DEBUG = int(parameters['debug'])
112                else:
113                        self.DEBUG = 0
114
115                if parameters.has_key('reply_address'):
116                        self.CC = int(parameters['reply_address'])
117                else:
118                        self.CC = 0
119
120                if parameters.has_key('mailto_link'):
121                        self.MAILTO = int(parameters['mailto_link'])
122                else:
123                        self.MAILTO = 0
124
125                if parameters.has_key('spam_level'):
126                        self.SPAM_LEVEL = int(parameters['spam_level'])
127                else:
128                        self.SPAM_LEVEL = 0
129
130                if parameters.has_key('email_comment'):
131                        self.comment = str(parameters['email_comment'])
132
133                if parameters.has_key('email_header'):
134                        self.EMAIL_HEADER = int(parameters['email_header'])
135                else:
136                        self.EMAIL_HEADER = 0
137
138
139        # X-Spam-Score: *** (3.255) BAYES_50,DNS_FROM_AHBL_RHSBL,HTML_
140        # Note if Spam_level then '*' are included
141        def spam(self, message):
142                if message.has_key('X-Spam-Score'):
143                        spam_l = string.split(message['X-Spam-Score'])
144                        number = spam_l[0].count('*')
145
146                        if number >= self.SPAM_LEVEL:
147                                return 'Spam'
148
149                return self.get_config('ticket', 'default_component')
150
151        def to_unicode(self, str):
152                """
153                Email has 7 bit ASCII code, convert it to unicode with the charset
154                that is encoded in 7-bit ASCII code and encode it as utf-8 so TRAC
155                understands it.
156                """
157                results =  Header.decode_header(str)
158                str = None
159                for text,format in results:
160                        if format:
161                                try:
162                                        temp = unicode(text, format)
163                                except UnicodeError:
164                                        # This always works
165                                        #
166                                        temp = unicode(text, 'iso-8859-15')
167                                temp =  temp.encode('utf-8')
168                        else:
169                                temp = string.strip(text)
170
171                        if str:
172                                str = '%s %s' %(str, temp)
173                        else:
174                                str = temp
175
176                return str
177
178        def debug_attachments(self, message):
179                n = 0
180                for part in message.walk():
181                        if part.get_content_maintype() == 'multipart':      # multipart/* is just a container
182                                print 'TD: multipart container'
183                                continue
184
185                        n = n + 1
186                        print 'TD: part%d: Content-Type: %s' % (n, part.get_content_type())
187                        print 'TD: part%d: filename: %s' % (n, part.get_filename())
188
189                        if part.is_multipart():
190                                print 'TD: this part is multipart'
191                                payload = part.get_payload(decode=1)
192                                print 'TD: payload:', payload
193                        else:
194                                print 'TD: this part is not multipart'
195
196                        part_file = '/var/tmp/part%d' % n
197                        print 'TD: writing part%d (%s)' % (n,part_file)
198                        fx = open(part_file, 'wb')
199                        text = part.get_payload(decode=1)
200                        if not text:
201                                text = '(None)'
202                        fx.write(text)
203                        fx.close()
204                        try:
205                                os.chmod(part_file,S_IRWXU|S_IRWXG|S_IRWXO)
206                        except OSError:
207                                pass
208
209        def email_header_txt(self, m):
210#               if not m['Subject']:
211#                       subject = '(geen subject)'
212#               else:
213#                       subject = self.to_unicode(m['Subject'])
214#
215#               head = "'''Subject:''' %s [[BR]]" % subject
216#               if m['From'] and len(m['From']) > 0:
217#                       head = "%s'''From:''' %s [[BR]]" % (head, m['From'])
218#               if m['Date'] and len(m['Date']) > 0:
219#                       head = "%s'''Date:''' %s [[BR]]" %(head, m['Date'])
220
221                str = ''
222                if m['To'] and len(m['To']) > 0 and m['To'] != 'hic@sara.nl':
223                        str = "'''To:''' %s [[BR]]" %(m['To'])
224                if m['Cc'] and len(m['Cc']) > 0:
225                        str = "%s'''Cc:''' %s [[BR]]" % (str, m['Cc'])
226
227                return str
228
229        def parse(self, fp):
230                msg = email.message_from_file(fp)
231                if not msg:
232                        return
233
234                if self.DEBUG > 1:        # save the entire e-mail message text
235                        msg_file = '/var/tmp/msg.txt'
236                        print 'TD: saving email to %s' % msg_file
237                        fx = open(msg_file, 'wb')
238                        fx.write('%s' % msg)
239                        fx.close()
240                        try:
241                                os.chmod(msg_file,S_IRWXU|S_IRWXG|S_IRWXO)
242                        except OSError:
243                                pass
244
245                self.db = self.env.get_db_cnx()
246                tkt = Ticket(self.env)
247                tkt['status'] = 'new'
248
249                # Some defaults
250                #
251                tkt['milestone'] = self.get_config('ticket', 'default_milestone')
252                tkt['priority'] = self.get_config('ticket', 'default_priority')
253                tkt['severity'] = self.get_config('ticket', 'default_severity')
254                tkt['version'] = self.get_config('ticket', 'default_version')
255
256                if not msg['Subject']:
257                        tkt['summary'] = '(geen subject)'
258                else:
259                        tkt['summary'] = self.to_unicode(msg['Subject'])
260
261
262                if settings.has_key('component'):
263                        tkt['component'] = settings['component']
264                else:
265                        tkt['component'] = self.spam(msg)
266
267                # Must make this an option or so, discard SPAM messages or save then
268                # and delete later
269                #
270                #if self.SPAM_LEVEL and self.spam(msg):
271                #       print 'This message is a SPAM. Automatic ticket insertion refused (SPAM level > %d' % self.SPAM_LEVEL
272                #       sys.exit(1)
273
274                # Get default owner for component
275                #
276                cursor = self.db.cursor()
277                sql = "SELECT owner FROM component WHERE name='%s'" % tkt['component']
278                cursor.execute(sql)
279                tkt['owner'] = cursor.fetchone()[0]
280
281                author, email_addr  = email.Utils.parseaddr(msg['from'])
282                email_str = self.to_unicode(email_addr)
283                if author:
284                        tkt['reporter'] = self.to_unicode(author)
285                else:
286                        tkt['reporter'] = self.to_unicode(email_str)
287
288                if self.CC:
289                        tkt['cc'] = email_str
290
291# produce e-mail like header
292                head = ''
293                if self.EMAIL_HEADER > 0:
294                        head = self.email_header_txt(msg)
295
296                if self.DEBUG > 0:
297                        self.debug_attachments(msg)
298
299#
300#       put the message text in the ticket description
301#       message text can be plain text or html or something else
302#
303                has_description = 0
304                for part in msg.walk():
305                        if part.get_content_maintype() == 'multipart':                  # 'multipart/*' is a container for multipart messages
306                                continue
307
308                        if part.get_content_type() == 'text/plain':
309                                body_text = part.get_payload(decode=1)                  # try to decode
310                                if not body_text:                                       # decode failed
311                                        body_text = part.get_payload(decode=0)          # do not decode
312
313                                tkt['description'] = '\n{{{\n\n%s\n}}}\n' % body_text
314
315                        elif part.get_content_type() == 'text/html':
316                                tkt['description'] = '%s\n\n(see attachment for HTML mail message)\n' % head
317                                body_text = tkt['description']
318
319                        else:
320                                tkt['description'] = '%s\n\n(see attachment for message)\n' % head
321                                body_text = tkt['description']
322
323                        has_description = 1
324                        break           # we have the description, so break
325
326                if not has_description:
327                        tkt['description'] = '%s\n\n(no plain text message, see attachments)' % head
328                        has_description = 1
329
330                if self.MAILTO:
331                        mailto = self.html_mailto_link(author, email_addr, self.to_unicode(msg['subject']), body_text)
332                        tkt['description'] = '%s\n%s %s' %(head, mailto, tkt['description'])
333
334                if self.VERSION > 0.8:
335                        tkt['id'] = tkt.insert()
336                else:
337                        tkt['id'] = tkt.insert(self.db)
338
339                #
340                # Just how to show to update description
341                #
342                #tkt['description'] = '\n{{{\n\n Bas is op nieuw bezig\n\n }}}\n'
343                #tkt.save_changes(self.db, author, "Lekker bezig")
344                #
345
346                self.attachments(msg, tkt, author)
347                if self.get_config('notification', 'smtp_enabled') in ['true']:
348                        self.notify(tkt)
349
350        def notify(self, tkt):
351                try:
352                        # create false {abs_}href properties, to trick Notify()
353                        #
354                        self.env.abs_href = Href(self.get_config('project', 'url'))
355                        self.env.href = Href(self.get_config('project', 'url'))
356
357                        tn = TicketNotifyEmail(self.env)
358                        tn.notify(tkt, newticket=True)
359
360                except Exception, e:
361                        print "TD: Failure sending notification on creation of ticket #%s: %s" % (tkt.id, e)
362
363        def mail_line(self, str):
364                return '%s %s' % (self.comment, str)
365
366
367        def html_mailto_link(self, author, mail_addr, subject, body):
368                if not author:
369                        author = mail_addr
370                else:   
371                        author = self.to_unicode(author)
372
373                # Must find a fix
374                #
375                #arr = string.split(body, '\n')
376                #arr = map(self.mail_line, arr)
377
378                #body = string.join(arr, '\n')
379                #body = '%s wrote:\n%s' %(author, body)
380
381                # Obsolete for reference
382                #
383                #body = self.to_unicode(body)
384                #body = urllib.quote(body)
385                #body = Header.encode(body)
386                #
387
388                # Temporary fix
389                body = '> Type your reply'
390                str = 'mailto:%s?subject=%s&body=%s' % (urllib.quote(mail_addr), urllib.quote('Re: %s' % subject), urllib.quote(body))
391                str = '\n{{{\n#!html\n<a href="%s">Reply to: %s</a>\n}}}\n' %(str, author)
392
393                return str
394
395        def attachments(self, message, ticket, user):
396                '''save any attachments as file in the ticket's directory'''
397
398                count = 0
399                first = 0
400                for part in message.walk():
401                        if part.get_content_maintype() == 'multipart':          # multipart/* is just a container
402                                continue
403
404                        if not first:                                                                           # first content is the message
405                                first = 1
406                                if part.get_content_type() == 'text/plain':             # if first is text, is was already put in the description
407                                        continue
408
409                        filename = part.get_filename()
410                        if not filename:
411                                count = count + 1
412                                filename = 'part%04d' % count
413
414                                ext = mimetypes.guess_extension(part.get_type())
415                                if not ext:
416                                        ext = '.bin'
417
418                                filename = '%s%s' % (filename, ext)
419                        else:
420                                filename = self.to_unicode(filename)
421
422                        if '/' in filename:
423                                filename = os.path.basename(filename)
424
425                        url_filename = urllib.quote(filename)
426
427                        if self.VERSION > 0.8:
428                                tmpfile = '/tmp/email2trac-ticket%sattachment' % str(ticket['id'])
429                        else:
430                                dir = os.path.join(self.env.get_attachments_dir(), 'ticket',
431                                                        urllib.quote(str(ticket['id'])))
432                                if not os.path.exists(dir):
433                                        mkdir_p(dir, 0755)
434
435                                tmpfile = os.path.join(dir, url_filename)
436
437                        f = open(tmpfile, 'wb')
438                        text = part.get_payload(decode=1)
439                        if not text:
440                                text = '(None)'
441                        f.write(text)
442
443                        # get the filesize
444                        #
445                        stats = os.lstat(tmpfile)
446                        filesize = stats[stat.ST_SIZE]
447
448                        # Insert the attachment it differs for the different TRAC versions
449                        #
450                        if self.VERSION > 0.8:
451                                att = attachment.Attachment(self.env,'ticket',ticket['id'])
452                                att.insert(url_filename,f,filesize)
453                                f.close()
454                        else:
455                                cursor = self.db.cursor()
456                                cursor.execute('INSERT INTO attachment VALUES("%s","%s","%s",%d,%d,"%s","%s","%s")'
457                                        %('ticket', urllib.quote(str(ticket['id'])), filename + '?format=raw', filesize,
458                                          int(time.time()),'', user, 'e-mail') )
459                                self.db.commit()
460
461
462def mkdir_p(dir, mode):
463        '''do a mkdir -p'''
464
465        arr = string.split(dir, '/')
466        path = ''
467        for part in arr:
468                path = '%s/%s' % (path, part)
469                try:
470                        stats = os.stat(path)
471                except OSError:
472                        os.mkdir(path, mode)
473
474
475def ReadConfig(file, name):
476        """
477        Parse the config file
478        """
479
480        if not os.path.isfile(file):
481                print 'File %s does not exists' %file
482                sys.exit(1)
483
484        config = ConfigParser.ConfigParser()
485        try:
486                config.read(file)
487        except ConfigParser.MissingSectionHeaderError,detail:
488                print detail
489                sys.exit(1)
490
491
492        # Use given project name else use defaults
493        #
494        if name:
495                if not config.has_section(name):
496                        print "Not an valid project name: %s" %name
497                        print "Valid names: %s" %config.sections()
498                        sys.exit(1)
499
500                project =  dict()
501                for option in  config.options(name):
502                        project[option] = config.get(name, option)
503
504        else:
505                project = config.defaults()
506
507        return project
508
509if __name__ == '__main__':
510        # Default config file
511        #
512        configfile = '@email2trac_conf@'
513        project = ''
514        component = ''
515       
516        try:
517                opts, args = getopt.getopt(sys.argv[1:], 'chf:p:', ['component=','help', 'file=', 'project='])
518        except getopt.error,detail:
519                print __doc__
520                print detail
521                sys.exit(1)
522
523        project_name = None
524        for opt,value in opts:
525                if opt in [ '-h', '--help']:
526                        print __doc__
527                        sys.exit(0)
528                elif opt in ['-c', '--component']:
529                        component = value
530                elif opt in ['-f', '--file']:
531                        configfile = value
532                elif opt in ['-p', '--project']:
533                        project_name = value
534
535        settings = ReadConfig(configfile, project_name)
536        if not settings.has_key('project'):
537                print __doc__
538                print 'No project defined in config file, eg:\n\t project: /data/trac/bas'
539                sys.exit(1)
540
541        if component:
542                settings['component'] = component
543
544        if settings.has_key('trac_version'):
545                version = float(settings['trac_version'])
546        else:
547                version = trac_default_version
548
549        #debug HvB
550        #print settings
551
552        if version > 0.8:
553                from trac import attachment
554                from trac.env import Environment
555                from trac.ticket import Ticket
556                from trac.Notify import TicketNotifyEmail
557                from trac.web.href import Href
558        else:
559                from trac.Environment import Environment
560                from trac.Ticket import Ticket
561                from trac.Notify import TicketNotifyEmail
562                from trac.Href import Href
563
564        env = Environment(settings['project'], create=0)
565        tktparser = TicketEmailParser(env, settings, version)
566        tktparser.parse(sys.stdin)
567
568# EOB
Note: See TracBrowser for help on using the repository browser.