Code

Attempt to generate more human-readable addresses in email
[roundup.git] / roundup / mailer.py
index 453a1ded0ed45c614eba34d5414bb0c6080e374a..729aaeab4d7200fbef196db904d53497f59fbde4 100644 (file)
@@ -9,7 +9,7 @@ from cStringIO import StringIO
 from roundup import __version__
 from roundup.date import get_timezone
 
-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,21 @@ 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
+    h = Header(charset=charset)
+    # the important bits of formataddr()
+    if specialsre.search(name):
+        name = '"%s"'%escapesre.sub(r'\\\g<0>', name)
+    try:
+        name.encode('ASCII')
+        h.append(name, 'ASCII')
+    except UnicodeEncodeError:
+        h.append(name)
+    h.append('<%s>'%address, 'ASCII')
+    return str(h)
+
 class Mailer:
     """Roundup-specific mail sending."""
     def __init__(self, config):
@@ -61,10 +76,11 @@ class Mailer:
         charset = getattr(self.config, 'EMAIL_CHARSET', 'utf-8')
         tracker_name = unicode(self.config.TRACKER_NAME, 'utf-8')
         if not author:
-            author = formataddr((tracker_name, self.config.ADMIN_EMAIL))
+            author = (tracker_name, self.config.ADMIN_EMAIL)
+            name = author[0]
         else:
             name = unicode(author[0], 'utf-8')
-            author = formataddr((name, author[1]))
+        author = nice_sender_header(name, author[1], charset)
 
         if multipart:
             message = MIMEMultipart()
@@ -77,10 +93,7 @@ class Mailer:
         except UnicodeError:
             message['Subject'] = Header(subject, charset)
         message['To'] = ', '.join(to)
-        try:
-            message['From'] = author.encode('ascii')
-        except UnicodeError:
-            message['From'] = Header(author, charset)
+        message['From'] = author
         message['Date'] = formatdate(localtime=True)
 
         # add a Precedence header so autoresponders ignore us