+

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

Benjamin Renard [2012-04-20 14:42:14]
MantisMail.get_text() : do not return html if plaintext version exists and convert html to text
Filename
src/usr/share/mantis-smtp/MantisMail.py
diff --git a/src/usr/share/mantis-smtp/MantisMail.py b/src/usr/share/mantis-smtp/MantisMail.py
index 843264e..95048c6 100755
--- a/src/usr/share/mantis-smtp/MantisMail.py
+++ b/src/usr/share/mantis-smtp/MantisMail.py
@@ -5,6 +5,7 @@ import re
 import string
 import smtplib
 import logging
+import html2text
 from email.MIMEText import MIMEText
 import email
 import email.header
@@ -29,11 +30,26 @@ class MantisMail(object):
 		return self.decode_header('Subject')

 	def get_text(self):
-		content='From : %s' % self.msg['From']
+		content=u'From : %s' % self.decode_header('From')
+		texts={}
 		for part in self.msg.walk():
 			if part.get_content_maintype() == 'text':
-				content='%s\n\n---------------------------\n\n%s' % (content,part.get_payload(decode=True))
-		return content
+				type=part.get_content_type()
+				if type not in texts:
+					texts[type]=[]
+				text=self.decode(part.get_payload(decode=True), prefer_encoding=part.get_content_charset())
+				if part.get_content_type() == 'text/html':
+					text=html2text.html2text(text)
+				texts[type].append(unicode(text))
+
+		if 'text/plain' in texts:
+			for text in texts['text/plain']:
+				content=u'%s\n\n---------------------------\n\n%s' % (content,text)
+		else:
+			for type in texts:
+				for text in texts[type]:
+					content=u'%s\n\n---------------------------\n\n%s' % (content,text)
+		return unicode(content)

 	def get_attachments(self):
 		attachments=[]
ViewGit