Mail & WS : Decode base64 attachments from mail and encode in base64 again for WS
Benjamin Renard

Benjamin Renard commited on 2012-04-20 14:46:09
Showing 2 changed files, with 16 additions and 3 deletions.

... ...
@@ -11,6 +11,7 @@ import email
11 11
 import email.header
12 12
 import mimetypes
13 13
 import sys
14
+import base64
14 15
 
15 16
 class MantisMail(object):
16 17
 
... ...
@@ -55,9 +56,10 @@ class MantisMail(object):
55 56
 		attachments=[]
56 57
 		counter=1
57 58
 		for part in self.msg.walk():
58
-			part_type = part.get_content_maintype()
59
-			if part_type == 'text' or part_type == 'multipart':
59
+			part_maintype = part.get_content_maintype()
60
+			if part_maintype == 'text' or part_maintype == 'multipart':
60 61
 				continue
62
+			part_type = part.get_content_type()
61 63
 			filename = part.get_filename()
62 64
 			if not filename:
63 65
 				ext = mimetypes.guess_extension(part.get_content_type())
... ...
@@ -66,6 +68,11 @@ class MantisMail(object):
66 68
 				filename = 'part-%03d%s' % (counter, ext)
67 69
 			counter += 1
68 70
 			content=part.get_payload(decode=False)
71
+			try:
72
+				content=base64.b64decode(content)
73
+			except Exception, e:
74
+				logging.error("Error decoding base64 content of file %s" % filename)
75
+				raise MantisMailError('base64_decode',"Error decoding base64 content of file %s" % filename)
69 76
 			attachments.append({
70 77
 				'filename':	filename,
71 78
 				'type':		part_type,
... ...
@@ -102,3 +109,8 @@ def send(mail_from,to,subject,content,smtp_host='127.0.0.1',smtp_port=25):
102 109
 		logging.error('Error sending mail to %s - %s : %s' % (to,subject,sys.exc_info()[0]))
103 110
                 return
104 111
 
112
+class MantisMailError(Exception):
113
+
114
+        def __init__(self,type,msg):
115
+                Exception.__init__(self, msg)
116
+                self.type = type
... ...
@@ -4,6 +4,7 @@ import suds
4 4
 import logging
5 5
 import re
6 6
 import MantisMail
7
+import base64
7 8
 
8 9
 class MantisWS(object):
9 10
 
... ...
@@ -60,7 +61,7 @@ class MantisWS(object):
60 61
 				issue_id,
61 62
 				attachment['filename'],
62 63
 				attachment['type'],
63
-				attachment['content']
64
+				base64.b64encode(attachment['content'])
64 65
 			)
65 66
 			return res
66 67
 		except suds.WebFault, e:
67 68