More work about webmail. It's almost possible to view emails content!

This commit is contained in:
tonio
2010-01-15 18:06:41 +01:00
parent 6c7a64e947
commit bf971301b6
14 changed files with 204 additions and 77 deletions
+71 -1
View File
@@ -1,7 +1,11 @@
# -*- coding: utf-8 -*-
import time
import lxml
from django.template.loader import render_to_string
from mailng.lib import _render
from django.template import Template
from mailng.lib import _render, decode
attached_map = {}
class MBconnector(object):
def __init__(self, address, port):
@@ -93,3 +97,69 @@ class EmailListing:
"selection" : self.folder,
"current_page" : pageid
})
class Email(object):
def __init__(self, msg, mode="plain", links="0"):
self.attached_map = {}
contents = {"html" : "", "plain" : ""}
for part in msg.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get_content_type() in ("text/html", "text/plain"):
contents[part.get_content_subtype()] += part.get_payload(decode=True)
if mode != "html" or links == "0":
continue
if part.get_content_maintype() == "image":
if part.has_key("Content-Location"):
fname = part["Content-Location"]
if re.match("^http:", fname):
path = fname
else:
path = "/%s" % os.path.join("static/tmp", fname)
fp = open(path, "wb")
fp.write(part.get_payload(decode=True))
fp.close()
m = re.match("<(.+)>", part["Content-ID"])
if m:
self.attached_map[m.group(1)] = path
else:
self.attached_map[part["Content-ID"]] = path
if not contents.has_key(mode) or contents[mode] == "":
if mode == "html":
mode = "plain"
else:
mode = "html"
self.pre, self.body = \
getattr(self, "viewmail_%s" % mode)(contents[mode], links=links)
def map_cid(self, url):
import re
map = globals()["attached_map"]
m = re.match(".*cid:([^\"]+)", url)
if m:
if map.has_key(m.group(1)):
return map[m.group(1)]
return url
def render(self, request):
return _render(request, 'common/getmailcontent.html', {
"body" : self.body, "pre" : self.pre
})
def viewmail_plain(self, content, **kwargs):
body = decode(content)
return (True, body)
def viewmail_html(self, content, **kwargs):
links = kwargs.has_key("links") and kwargs["links"] or "0"
html = lxml.html.fromstring(content)
if links == "0":
html.rewrite_links(lambda x: None)
else:
html.rewrite_links(self.map_cid)
body = lxml.html.tostring(html)
body = Template(decode(body)).render({})
return (False, body)