Use "pyramid_mailer" Message class
authorThierry Florac <thierry.florac@onf.fr>
Thu, 02 Jun 2016 15:46:08 +0200
changeset 5 ac54083bbe98
parent 4 2c6816d5a41b
child 6 8927221a0675
Use "pyramid_mailer" Message class
src/pyams_mail/message.py
--- a/src/pyams_mail/message.py	Thu Jun 02 15:45:37 2016 +0200
+++ b/src/pyams_mail/message.py	Thu Jun 02 15:46:08 2016 +0200
@@ -14,18 +14,14 @@
 
 
 # import standard library
-import chardet
 import codecs
-from datetime import datetime
-from email.mime.multipart import MIMEMultipart
-from email.mime.text import MIMEText
 from html import entities
 
 # import interfaces
 
 # import packages
 from pyams_utils.html import html_to_text
-from pyams_utils.timezone import gmtime
+from pyramid_mailer.message import Message
 
 
 def html_replace(exc):
@@ -41,44 +37,26 @@
     return unicode_data.encode(encoding, 'html_replace')
 
 
-def HTMLMessage(subject, fromaddr, toaddr, html, text=None):
-    """Create a MIME message that will render as HTML or text
-
-    Copied from 'Python Cookbook', chapter 13.5"""
-    html = html_encode(html)
+def HTMLMessage(subject, fromaddr, toaddr, html, text=None, encoding='utf-8'):
+    """Create a MIME message that will render as HTML or text"""
+    html = html_encode(html, encoding).decode(encoding)
     if text is None:
         # produce textual rendering of the HTML string when None is provided
         text = html_to_text(html)
-    msg = MIMEMultipart()
-    msg['Subject'] = subject
-    msg['Date'] = gmtime(datetime.utcnow()).strftime('%a, %d %b %Y %H:%M:%S %z (%Z)')
-    msg['From'] = fromaddr
     if isinstance(toaddr, str):
         toaddr = (toaddr, )
-    msg['To'] = ', '.join(toaddr)
-    parts = MIMEMultipart('alternative')
-    plain_part = MIMEText(text, 'plain')
-    plain_part.set_charset('utf-8')
-    html_part = MIMEText(html, 'html')
-    html_part.set_charset('utf-8')
-    parts.attach(plain_part)
-    parts.attach(html_part)
-    msg.attach(parts)
-    return msg
+    return Message(subject=subject,
+                   sender=fromaddr,
+                   recipients=toaddr,
+                   html=html,
+                   body=text)
 
 
 def TextMessage(subject, fromaddr, toaddr, text):
     """Create a text message"""
-    msg = MIMEMultipart()
-    msg['Subject'] = subject
-    msg['Date'] = gmtime(datetime.utcnow()).strftime('%a, %d %b %Y %H:%M:%S %z (%Z)')
-    msg['From'] = fromaddr
     if isinstance(toaddr, str):
         toaddr = (toaddr, )
-    msg['To'] = ', '.join(toaddr)
-    if isinstance(text, str):
-        text = text.encode()
-    charset = chardet.detect(text).get('encoding', 'utf-8')
-    plain_part = MIMEText(text, 'plain', charset)
-    msg.attach(plain_part)
-    return msg
+    return Message(subject=subject,
+                   sender=fromaddr,
+                   recipients=toaddr,
+                   body=text)