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

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

EmailtoTracScript?:

email2trac:

  • Use only email address in CC field Thanks to Kilian CAVALOTTI
  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 14.4 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 39 2006-01-24 22:46:08Z 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.new_ticket = ticket.Ticket
104                        self.get_config = self.env.config.get
105                else:
106                        self.new_ticket = Ticket.Ticket
107                        self.get_config = self.env.get_config
108
109                if parameters.has_key('umask'):
110                        os.umask(int(parameters['umask'], 8))
111
112                if parameters.has_key('debug'):
113                        self.DEBUG = int(parameters['debug'])
114                else:
115                        self.DEBUG = 0
116
117                if parameters.has_key('reply_address'):
118                        self.CC = int(parameters['reply_address'])
119                else:
120                        self.CC = 0
121
122                if parameters.has_key('mailto_link'):
123                        self.MAILTO = int(parameters['mailto_link'])
124                else:
125                        self.MAILTO = 0
126
127                if parameters.has_key('spam_level'):
128                        self.SPAM_LEVEL = int(parameters['spam_level'])
129                else:
130                        self.SPAM_LEVEL = 0
131
132                if parameters.has_key('email_comment'):
133                        self.comment = str(parameters['email_comment'])
134
135                if parameters.has_key('email_header'):
136                        self.EMAIL_HEADER = int(parameters['email_header'])
137                else:
138                        self.EMAIL_HEADER = 0
139
140
141        # X-Spam-Score: *** (3.255) BAYES_50,DNS_FROM_AHBL_RHSBL,HTML_
142        # Note if Spam_level then '*' are included
143        def spam(self, message):
144                if message.has_key('X-Spam-Score'):
145                        spam_l = string.split(message['X-Spam-Score'])
146                        number = spam_l[0].count('*')
147
148                        if number >= self.SPAM_LEVEL:
149                                return number
150
151                return 0
152
153        def to_unicode(self, str):
154                """
155                Email has 7 bit ASCII code, convert it to unicode with the charset
156                that is encoded in 7-bit ASCII code and encode it as utf-8 so TRAC
157                understands it.
158                """
159                results =  Header.decode_header(str)
160                str = None
161                for text,format in results:
162                        if format:
163                                try:
164                                        temp = unicode(text, format)
165                                except UnicodeError:
166                                        # This always works
167                                        #
168                                        temp = unicode(text, 'iso-8859-15')
169                                temp =  temp.encode('utf-8')
170                        else:
171                                temp = string.strip(text)
172
173                        if str:
174                                str = '%s %s' %(str, temp)
175                        else:
176                                str = temp
177
178                return str
179
180        def debug_attachments(self, message):
181                n = 0
182                for part in message.walk():
183                        if part.get_content_maintype() == 'multipart':      # multipart/* is just a container
184                                print 'TD: multipart container'
185                                continue
186
187                        n = n + 1
188                        print 'TD: part%d: Content-Type: %s' % (n, part.get_content_type())
189                        print 'TD: part%d: filename: %s' % (n, part.get_filename())
190
191                        if part.is_multipart():
192                                print 'TD: this part is multipart'
193                                payload = part.get_payload(decode=1)
194                                print 'TD: payload:', payload
195                        else:
196                                print 'TD: this part is not multipart'
197
198                        part_file = '/var/tmp/part%d' % n
199                        print 'TD: writing part%d (%s)' % (n,part_file)
200                        fx = open(part_file, 'wb')
201                        text = part.get_payload(decode=1)
202                        if not text:
203                                text = '(None)'
204                        fx.write(text)
205                        fx.close()
206                        try:
207                                os.chmod(part_file,S_IRWXU|S_IRWXG|S_IRWXO)
208                        except OSError:
209                                pass
210
211        def email_header_txt(self, m):
212#               if not m['Subject']:
213#                       subject = '(geen subject)'
214#               else:
215#                       subject = self.to_unicode(m['Subject'])
216#
217#               head = "'''Subject:''' %s [[BR]]" % subject
218#               if m['From'] and len(m['From']) > 0:
219#                       head = "%s'''From:''' %s [[BR]]" % (head, m['From'])
220#               if m['Date'] and len(m['Date']) > 0:
221#                       head = "%s'''Date:''' %s [[BR]]" %(head, m['Date'])
222
223                str = ''
224                if m['To'] and len(m['To']) > 0 and m['To'] != 'hic@sara.nl':
225                        str = "'''To:''' %s [[BR]]" %(m['To'])
226                if m['Cc'] and len(m['Cc']) > 0:
227                        str = "%s'''Cc:''' %s [[BR]]" % (str, m['Cc'])
228
229                return str
230
231        def parse(self, fp):
232                msg = email.message_from_file(fp)
233                if not msg:
234                        return
235
236                if self.DEBUG > 1:        # save the entire e-mail message text
237                        msg_file = '/var/tmp/msg.txt'
238                        print 'TD: saving email to %s' % msg_file
239                        fx = open(msg_file, 'wb')
240                        fx.write('%s' % msg)
241                        fx.close()
242                        try:
243                                os.chmod(msg_file,S_IRWXU|S_IRWXG|S_IRWXO)
244                        except OSError:
245                                pass
246
247                self.db = self.env.get_db_cnx()
248                tkt = self.new_ticket(self.env)
249                tkt['status'] = 'new'
250
251                # Some defaults
252                #
253                tkt['milestone'] = self.get_config('ticket', 'default_milestone')
254                tkt['priority'] = self.get_config('ticket', 'default_priority')
255                tkt['severity'] = self.get_config('ticket', 'default_severity')
256                tkt['version'] = self.get_config('ticket', 'default_version')
257
258                if not msg['Subject']:
259                        tkt['summary'] = '(geen subject)'
260                else:
261                        tkt['summary'] = self.to_unicode(msg['Subject'])
262
263
264                if self.SPAM_LEVEL:
265                        tkt['component'] = self.spam(msg)
266                elif settings.has_key('component'):
267                        tkt['component'] = settings['component']
268                else:
269                        tkt['component'] = self.get_config('ticket', 'default_component')
270
271                # Must make this an option or so, discard SPAM messages or save then
272                # and delete later
273                #
274                #if self.SPAM_LEVEL and self.spam(msg):
275                #       print 'This message is a SPAM. Automatic ticket insertion refused (SPAM level > %d' % self.SPAM_LEVEL
276                #       sys.exit(1)
277
278                # Get default owner for component
279                #
280                cursor = self.db.cursor()
281                sql = 'SELECT owner FROM component WHERE name=\'%s\'' % tkt['component']
282                cursor.execute(sql)
283                tkt['owner'] = cursor.fetchone()[0]
284
285                author, email_addr  = email.Utils.parseaddr(msg['from'])
286                from_str = self.to_unicode(msg['from'])
287                tkt['reporter'] = from_str
288                if self.CC:
289                        tkt['cc'] = email_addr
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                self.attachments(msg, tkt, author)
346
347
348        def mail_line(self, str):
349                return '%s %s' % (self.comment, str)
350
351
352        def html_mailto_link(self, author, mail_addr, subject, body):
353                if not author:
354                        author = mail_addr
355                else:   
356                        author = self.to_unicode(author)
357
358                # Must find a fix
359                #
360                #arr = string.split(body, '\n')
361                #arr = map(self.mail_line, arr)
362
363                #body = string.join(arr, '\n')
364                #body = '%s wrote:\n%s' %(author, body)
365
366                # Obsolete for reference
367                #
368                #body = self.to_unicode(body)
369                #body = urllib.quote(body)
370                #body = Header.encode(body)
371                #
372
373                # Temporary fix
374                body = '> Type your reply'
375                str = 'mailto:%s?subject=%s&body=%s' % (urllib.quote(mail_addr), urllib.quote('Re: %s' % subject), urllib.quote(body))
376                str = '\n{{{\n#!html\n<a href="%s">Reply to: %s</a>\n}}}\n' %(str, author)
377
378                return str
379
380        def attachments(self, message, ticket, user):
381                '''save any attachments as file in the ticket's directory'''
382
383                count = 0
384                first = 0
385                for part in message.walk():
386                        if part.get_content_maintype() == 'multipart':          # multipart/* is just a container
387                                continue
388
389                        if not first:                                                                           # first content is the message
390                                first = 1
391                                if part.get_content_type() == 'text/plain':             # if first is text, is was already put in the description
392                                        continue
393
394                        filename = part.get_filename()
395                        if not filename:
396                                count = count + 1
397                                filename = 'part%04d' % count
398
399                                ext = mimetypes.guess_extension(part.get_type())
400                                if not ext:
401                                        ext = '.bin'
402
403                                filename = '%s%s' % (filename, ext)
404                        else:
405                                filename = self.to_unicode(filename)
406
407                        if '/' in filename:
408                                filename = os.path.basename(filename)
409
410                        url_filename = urllib.quote(filename)
411
412                        if self.VERSION > 0.8:
413                                tmpfile = '/tmp/email2trac-ticket%sattachment' % str(ticket['id'])
414                        else:
415                                dir = os.path.join(self.env.get_attachments_dir(), 'ticket',
416                                                        urllib.quote(str(ticket['id'])))
417                                if not os.path.exists(dir):
418                                        mkdir_p(dir, 0755)
419
420                                tmpfile = os.path.join(dir, url_filename)
421
422                        f = open(tmpfile, 'wb')
423                        text = part.get_payload(decode=1)
424                        if not text:
425                                text = '(None)'
426                        f.write(text)
427
428                        # get the filesize
429                        #
430                        stats = os.lstat(tmpfile)
431                        filesize = stats[stat.ST_SIZE]
432
433                        # Insert the attachment it differs for the different TRAC versions
434                        #
435                        if self.VERSION > 0.8:
436                                att = attachment.Attachment(self.env,'ticket',ticket['id'])
437                                att.insert(url_filename,f,filesize)
438                                f.close()
439                        else:
440                                cursor = self.db.cursor()
441                                cursor.execute('INSERT INTO attachment VALUES("%s","%s","%s",%d,%d,"%s","%s","%s")'
442                                        %('ticket', urllib.quote(str(ticket['id'])), filename + '?format=raw', filesize,
443                                          int(time.time()),'', user, 'e-mail') )
444                                self.db.commit()
445
446
447def mkdir_p(dir, mode):
448        '''do a mkdir -p'''
449
450        arr = string.split(dir, '/')
451        path = ''
452        for part in arr:
453                path = '%s/%s' % (path, part)
454                try:
455                        stats = os.stat(path)
456                except OSError:
457                        os.mkdir(path, mode)
458
459
460def ReadConfig(file, name):
461        """
462        Parse the config file
463        """
464
465        if not os.path.isfile(file):
466                print 'File %s does not exists' %file
467                sys.exit(1)
468
469        config = ConfigParser.ConfigParser()
470        try:
471                config.read(file)
472        except ConfigParser.MissingSectionHeaderError,detail:
473                print detail
474                sys.exit(1)
475
476
477        # Use given project name else use defaults
478        #
479        if name:
480                if not config.has_section(name):
481                        print "Not an valid project name: %s" %name
482                        print "Valid names: %s" %config.sections()
483                        sys.exit(1)
484
485                project =  dict()
486                for option in  config.options(name):
487                        project[option] = config.get(name, option)
488
489        else:
490                project = config.defaults()
491
492        return project
493
494if __name__ == '__main__':
495        # Default config file
496        #
497        configfile = '@email2trac_conf@'
498        project = ''
499        component = ''
500       
501        try:
502                opts, args = getopt.getopt(sys.argv[1:], 'chf:p:', ['component=','help', 'file=', 'project='])
503        except getopt.error,detail:
504                print __doc__
505                print detail
506                sys.exit(1)
507
508        project_name = None
509        for opt,value in opts:
510                if opt in [ '-h', '--help']:
511                        print __doc__
512                        sys.exit(0)
513                elif opt in ['-c', '--component']:
514                        component = value
515                elif opt in ['-f', '--file']:
516                        configfile = value
517                elif opt in ['-p', '--project']:
518                        project_name = value
519
520        settings = ReadConfig(configfile, project_name)
521        if not settings.has_key('project'):
522                print __doc__
523                print 'No project defined in config file, eg:\n\t project: /data/trac/bas'
524                sys.exit(1)
525
526        if component:
527                settings['component'] = component
528
529        if settings.has_key('trac_version'):
530                version = float(settings['trac_version'])
531        else:
532                version = trac_default_version
533
534        #debug HvB
535        #print settings
536
537        if version > 0.8:
538                from trac import attachment, config, env, ticket
539                env = env.Environment(settings['project'], create=0)
540                ticket_mod = ticket
541        else:
542                from trac import Environment, Ticket
543                env = Environment.Environment(settings['project'], create=0)
544                ticket_mod = Ticket
545               
546        tktparser = TicketEmailParser(env, settings, version)
547        tktparser.parse(sys.stdin)
548
549# EOB
Note: See TracBrowser for help on using the repository browser.