Code

Allow to turn off translation of generated html options in menu method
[roundup.git] / roundup / mailer.py
index f1a1af3bdf45a20f469dd7132b022449cf922df1..a91baf2cee5ebfeaf705c09c6e8c6a3285d29f9a 100644 (file)
@@ -7,9 +7,9 @@ import time, quopri, os, socket, smtplib, re, sys, traceback, email
 from cStringIO import StringIO
 
 from roundup import __version__
-from roundup.date import get_timezone
+from roundup.date import get_timezone, Date
 
-from email.Utils import formatdate, formataddr
+from email.Utils import formatdate, formataddr, specialsre, escapesre
 from email.Message import Message
 from email.Header import Header
 from email.MIMEText import MIMEText
@@ -25,6 +25,25 @@ def encode_quopri(msg):
     del msg['Content-Transfer-Encoding']
     msg['Content-Transfer-Encoding'] = 'quoted-printable'
 
+def nice_sender_header(name, address, charset):
+    # construct an address header so it's as human-readable as possible
+    # even in the presence of a non-ASCII name part
+    if not name:
+        return address
+    try:
+        encname = name.encode('ASCII')
+    except UnicodeEncodeError:
+        # use Header to encode correctly.
+        encname = Header(name, charset=charset).encode()
+
+    # the important bits of formataddr()
+    if specialsre.search(encname):
+        encname = '"%s"'%escapesre.sub(r'\\\g<0>', encname)
+
+    # now format the header as a string - don't return a Header as anonymous
+    # headers play poorly with Messages (eg. won't get wrapped properly)
+    return '%s <%s>'%(encname, address)
+
 class Mailer:
     """Roundup-specific mail sending."""
     def __init__(self, config):
@@ -65,11 +84,7 @@ class Mailer:
             name = author[0]
         else:
             name = unicode(author[0], 'utf-8')
-        try:
-            name = name.encode('ascii')
-        except UnicodeError:
-            name = Header(name, charset).encode()
-        author = formataddr((name, author[1]))
+        author = nice_sender_header(name, author[1], charset)
 
         if multipart:
             message = MIMEMultipart()
@@ -192,9 +207,12 @@ class Mailer:
         if not sender:
             sender = self.config.ADMIN_EMAIL
         if self.debug:
-            # don't send - just write to a file
-            open(self.debug, 'a').write('FROM: %s\nTO: %s\n%s\n' %
-                                        (sender,
+            # don't send - just write to a file, use unix from line so
+            # that resulting file can be openened in a mailer
+            fmt = '%a %b %m %H:%M:%S %Y'
+            unixfrm = 'From %s %s' % (sender, Date ('.').pretty (fmt))
+            open(self.debug, 'a').write('%s\nFROM: %s\nTO: %s\n%s\n\n' %
+                                        (unixfrm, sender,
                                          ', '.join(to), message))
         else:
             # now try to send the message