Zionetrix::Git
Repositories
Help
Report an Issue
mantisbt-smtp-gateway
Code
Commits
Branches
Tags
Search
Tree:
c90e41a
Branches
Tags
master
mantisbt-smtp-gateway
src
usr
share
mantis-smtp
MantisMail.py
MantisMail : fix sys import for method send()
Benjamin Renard
commited
c90e41a
at 2012-04-20 14:38:42
MantisMail.py
Blame
History
Raw
#!/usr/bin/python # -*- coding: utf-8 -*- import re import string import smtplib import logging 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='From : %s' % self.msg['From'] 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 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