Zionetrix::Git
Repositories
Help
Report an Issue
mantisbt-smtp-gateway
Code
Commits
Branches
Tags
Search
Tree:
a31cba4
Branches
Tags
master
mantisbt-smtp-gateway
src
usr
share
mantis-smtp
MantisMail.py
MantisMail.get_text() : do not return html if plaintext version exists and convert html to text
Benjamin Renard
commited
a31cba4
at 2012-04-20 14:42:14
MantisMail.py
Blame
History
Raw
#!/usr/bin/python # -*- coding: utf-8 -*- import re import string import smtplib import logging import html2text from email.MIMEText import MIMEText import email import email.header import mimetypes import sys class MantisMail(object): def __init__(self,mailfrom,mailto,data): self.mailfrom = mailfrom self.mailto = mailto self.msg = email.message_from_string(data) def get_issue_id_from_subject(self): res=re.search('\[[^\]]* ([0-9]*)\]',self.subject()) if res: issue_id=res.group(1) return string.atoi(issue_id) return None def subject(self): return self.decode_header('Subject') def get_text(self): content=u'From : %s' % self.decode_header('From') texts={} for part in self.msg.walk(): if part.get_content_maintype() == 'text': 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=[] counter=1 for part in self.msg.walk(): part_type = part.get_content_maintype() if part_type == 'text' or part_type == 'multipart': continue filename = part.get_filename() if not filename: ext = mimetypes.guess_extension(part.get_content_type()) if not ext: ext = '.bin' filename = 'part-%03d%s' % (counter, ext) counter += 1 content=part.get_payload(decode=False) attachments.append({ 'filename': filename, 'type': part_type, 'content': content }) return attachments def decode(self,text, prefer_encoding=None): try_enc=['iso-8859-15', 'utf-8'] if prefer_encoding: try_enc.insert(0,prefer_encoding) for i in try_enc: try: return unicode(text.decode(i)) except Exception, e: continue return unicode(text.decode('utf-8', errors = 'replace')) def decode_header(self,header): s=email.Header.decode_header(self.msg[header])[0] return self.decode(s[0],prefer_encoding=s[1]) def send(mail_from,to,subject,content,smtp_host='127.0.0.1',smtp_port=25): msg = MIMEText(content) msg['To'] = to msg['From'] = mail_from msg['Subject'] = subject server = smtplib.SMTP(smtp_host,smtp_port) try: server.sendmail(mail_from, [to], msg.as_string()) except: logging.error('Error sending mail to %s - %s : %s' % (to,subject,sys.exc_info()[0])) return