MantisMail.get_text() : do not return html if plaintext version exists and convert html to text
Benjamin Renard

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

... ...
@@ -5,6 +5,7 @@ import re
5 5
 import string
6 6
 import smtplib
7 7
 import logging
8
+import html2text
8 9
 from email.MIMEText import MIMEText
9 10
 import email
10 11
 import email.header
... ...
@@ -29,11 +30,26 @@ class MantisMail(object):
29 30
 		return self.decode_header('Subject')
30 31
 	
31 32
 	def get_text(self):
32
-		content='From : %s' % self.msg['From']
33
+		content=u'From : %s' % self.decode_header('From')
34
+		texts={}
33 35
 		for part in self.msg.walk():
34 36
 			if part.get_content_maintype() == 'text':
35
-				content='%s\n\n---------------------------\n\n%s' % (content,part.get_payload(decode=True))
36
-		return content
37
+				type=part.get_content_type()
38
+				if type not in texts:
39
+					texts[type]=[]
40
+				text=self.decode(part.get_payload(decode=True), prefer_encoding=part.get_content_charset())
41
+				if part.get_content_type() == 'text/html':
42
+					text=html2text.html2text(text)
43
+				texts[type].append(unicode(text))
44
+
45
+		if 'text/plain' in texts:
46
+			for text in texts['text/plain']:
47
+				content=u'%s\n\n---------------------------\n\n%s' % (content,text)
48
+		else:
49
+			for type in texts:
50
+				for text in texts[type]:
51
+					content=u'%s\n\n---------------------------\n\n%s' % (content,text)
52
+		return unicode(content)
37 53
 	
38 54
 	def get_attachments(self):
39 55
 		attachments=[]
40 56