MantisMail : Added decode() and decode_header() methods
Benjamin Renard

Benjamin Renard commited on 2012-04-20 14:32:46
Showing 1 changed files, with 19 additions and 3 deletions.

... ...
@@ -1,12 +1,13 @@
1 1
 #!/usr/bin/python
2
+# -*- coding: utf-8 -*-
2 3
 
3
-import email
4 4
 import re
5 5
 import string
6
-from email.MIMEText import MIMEText
7 6
 import smtplib
8 7
 import logging
9
-
8
+from email.MIMEText import MIMEText
9
+import email
10
+import email.header
10 11
 
11 12
 class MantisMail(object):
12 13
 
... ...
@@ -54,6 +55,21 @@ class MantisMail(object):
54 55
 			})
55 56
 		return attachments
56 57
 
58
+	def decode(self,text, prefer_encoding=None):
59
+		try_enc=['iso-8859-15', 'utf-8']
60
+		if prefer_encoding:
61
+			try_enc.insert(0,prefer_encoding)
62
+		for i in try_enc:
63
+			try:
64
+				return unicode(text.decode(i))
65
+			except Exception, e:
66
+				continue
67
+		return unicode(text.decode('utf-8', errors = 'replace'))
68
+
69
+	def decode_header(self,header):
70
+		s=email.Header.decode_header(self.msg[header])[0]
71
+		return self.decode(s[0],prefer_encoding=s[1])
72
+
57 73
 def send(mail_from,to,subject,content,smtp_host='127.0.0.1',smtp_port=25):
58 74
 	msg = MIMEText(content)
59 75
 	msg['To'] = to
60 76