Code

When debugging mail (debug = <filename> setting in [mail] section of
[roundup.git] / roundup / mailer.py
index 729aaeab4d7200fbef196db904d53497f59fbde4..a91baf2cee5ebfeaf705c09c6e8c6a3285d29f9a 100644 (file)
@@ -7,7 +7,7 @@ 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, specialsre, escapesre
 from email.Message import Message
@@ -28,17 +28,21 @@ def encode_quopri(msg):
 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)
+    if not name:
+        return address
     try:
-        name.encode('ASCII')
-        h.append(name, 'ASCII')
+        encname = name.encode('ASCII')
     except UnicodeEncodeError:
-        h.append(name)
-    h.append('<%s>'%address, 'ASCII')
-    return str(h)
+        # 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."""
@@ -203,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