emencia / emencia-django-newsletter

An app for sending newsletter by email to a contact list.
189 stars 72 forks source link

correct html2text links wrapping #30

Closed alexgarel closed 13 years ago

alexgarel commented 13 years ago

https://github.com/aaronsw/html2text/issues/#issue/7 is an issue for text format of mails with long urls. The mail client truncate wrapped urls.

I'll post here a patch to circumvent the problem in EDN.

alexgarel commented 13 years ago
--- a/emencia/django/newsletter/mailer.py
+++ b/emencia/django/newsletter/mailer.py
@@ -2,6 +2,8 @@
 import mimetypes

 from random import sample
+import re
+from StringIO import StringIO
 from smtplib import SMTPRecipientsRefused
 from datetime import datetime

@@ -20,7 +22,7 @@ except ImportError:  # Python 2.4 compatibility
     from email.MIMEBase import MIMEBase
     from email.MIMEImage import MIMEImage
 from email import message_from_file
-from html2text import html2text
+from html2text import html2text as html2text_orig
 from django.contrib.sites.models import Site
 from django.template import Context, Template
 from django.template.loader import render_to_string
@@ -38,6 +40,24 @@ from emencia.django.newsletter.settings import UNIQUE_KEY_LEN
 from emencia.django.newsletter.settings import UNIQUE_KEY_CHAR_SET
 from emencia.django.newsletter.settings import INCLUDE_UNSUBSCRIPTION

+link_re = re.compile(r"https?://([^ \n]+\n)+[^ \n]+", re.MULTILINE)
+
+def html2text(html):
+    """use html2text but repair newlines cutting urls"""
+    txt = html2text_orig(html)
+    links = list(link_re.finditer(txt))
+    # replace links
+    out = StringIO()
+    pos = 0 # position in txt
+    for l in links:
+        out.write(txt[pos:l.start()])
+        out.write(l.group().replace("\n",""))
+        pos = l.end()
+    out.write(txt[pos:])
+    return out.getvalue() 
+      

 class Mailer(object):
     """Mailer for generating and sending newsletters
Fantomas42 commented 13 years ago

Hi alexgarel,

tjank you for the patch, applied in Fantomas42/emencia-django-newsletter@a9adff758e56b949db8c1952bf3da541bf87fd47