import re import email.Utils def wrap(text, width): """ A word-wrap function that preserves existing line breaks and most spaces in the text. Expects that existing line breaks are posix newlines (\n). From: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061 """ return reduce(lambda line, word, width=width: '%s%s%s' % (line, ' \n'[(len(line)-line.rfind('\n')-1 + len(word.split('\n',1)[0] ) >= width)], word), text.split(' ') ) def get_from_addr(addr): """ Parses the From: header Returns the name, email address, or the string it was given (in that order) """ parsedfrom = email.Utils.parseaddr(addr) if parsedfrom[0] != '': return parsedfrom[0] elif parsedfrom[1] != '': return parsedfrom[1] else: return addr def findlinks(s): """ returns a list of all http:// or https:// links in the input string """ p = re.compile(".*(http[s]?\S+)", re.M) links = [] for line in s.splitlines(): m = p.match(line) try: for l in m.groups(): links.append(l) except: pass return links def makelinks(s): """ Converts plain text http[s]:// addresses to equivalents """ for link in findlinks(s): s = s.replace(link, "%s" % (link, link)) return s