From 08e45d4c34a1a162e9558224ac418a5fd825b8a3 Mon Sep 17 00:00:00 2001
From: Caetan <caetan.tojeiro.carpente@cern.ch>
Date: Thu, 5 Nov 2020 11:47:40 +0100
Subject: [PATCH] [#5]Implement-email-processor-logic-and-email-templates

---
 .flake8                                       |  2 +
 notifications_consumer/config.py              |  9 +++-
 .../processors/email/processor.py             | 25 ++++++++++
 .../processors/email/templates/sample.html    |  7 ---
 .../processors/email/templates/sample.txt     |  5 --
 .../email/templates/simple_notification.html  | 47 +++++++++++++++++++
 .../email/templates/simple_notification.txt   |  4 ++
 .../processors/email/utils.py                 |  9 ++--
 scripts/docker-send-email.py                  |  6 ++-
 scripts/send-email-test-example.py            |  4 +-
 10 files changed, 96 insertions(+), 22 deletions(-)
 delete mode 100644 notifications_consumer/processors/email/templates/sample.html
 delete mode 100644 notifications_consumer/processors/email/templates/sample.txt
 create mode 100644 notifications_consumer/processors/email/templates/simple_notification.html
 create mode 100644 notifications_consumer/processors/email/templates/simple_notification.txt

diff --git a/.flake8 b/.flake8
index dbb2240..5dc6e60 100644
--- a/.flake8
+++ b/.flake8
@@ -5,3 +5,5 @@ exclude = vendor,notifications_consumer/processors/email/templates
 per-file-ignores =
     # Imported but unused
     notifications_consumer/processors/__init__.py: F401
+    # Line too long
+    scripts/docker-send-email.py: E501
diff --git a/notifications_consumer/config.py b/notifications_consumer/config.py
index 5c1fd23..3224522 100644
--- a/notifications_consumer/config.py
+++ b/notifications_consumer/config.py
@@ -28,8 +28,13 @@ class Config:
     EMAIL_USE_SSL = ast.literal_eval(os.getenv("EMAIL_USE_SSL", "False"))
     EMAIL_TIMEOUT = int(os.getenv("EMAIL_TIMEOUT", "10"))
 
-    EMAIL_BACKEND = "vendor.django_mail.backends.console.EmailBackend"
-    NOREPLY_ADDRESS = os.getenv("NOREPLY_ADDRESS", "noreply@example.com")
+    EMAIL_BACKEND = os.getenv(
+        "EMAIL_BACKEND", "vendor.django_mail.backends.console.EmailBackend"
+    )
+    NOREPLY_ADDRESS = os.getenv("NOREPLY_ADDRESS", "noreply@cern.ch")
+
+    # Service
+    SERVICE_NAME = os.getenv("SERVICE_NAME", "Notifications Service")
 
     TEMPLATES = Environment(
         loader=PrefixLoader(
diff --git a/notifications_consumer/processors/email/processor.py b/notifications_consumer/processors/email/processor.py
index 851449e..ae05c8d 100644
--- a/notifications_consumer/processors/email/processor.py
+++ b/notifications_consumer/processors/email/processor.py
@@ -2,6 +2,8 @@
 import logging
 from typing import Dict
 
+from notifications_consumer.config import Config
+from notifications_consumer.processors.email.utils import create_email, send_emails
 from notifications_consumer.processors.processor import Processor
 from notifications_consumer.processors.registry import ProcessorRegistry
 
@@ -25,8 +27,31 @@ class EmailProcessor(Processor):
         """Process the message and send an email."""
         logging.debug(f"I'm the {self} and i'm consuming with {kwargs}")
 
+        recipient_email = kwargs["email"]
+        subject = kwargs["summary"]
+        sender_name = Config.SERVICE_NAME
+        context = {
+            "message_body": kwargs["message_body"],
+            "sender": sender_name,
+        }
+
+        text_template = Config.TEMPLATES.get_template("email/simple_notification.txt")
+        html_template = Config.TEMPLATES.get_template("email/simple_notification.html")
+        attachments = None
+        email = create_email(
+            [recipient_email],
+            subject,
+            text_template,
+            html_template,
+            context,
+            attachments,
+        )
+
+        return send_emails([email])
+
     def read_message(self, message: Dict):
         """Read the message."""
         logging.debug(f"I'm the {self} and i'm reading the message")
+        logging.debug(message)
 
         return message
diff --git a/notifications_consumer/processors/email/templates/sample.html b/notifications_consumer/processors/email/templates/sample.html
deleted file mode 100644
index 87bdb47..0000000
--- a/notifications_consumer/processors/email/templates/sample.html
+++ /dev/null
@@ -1,7 +0,0 @@
-<body>
-    Hello {{ name }},
-    How are you?
-
-    Cheers,
-    {{ sender }}
-</body>
diff --git a/notifications_consumer/processors/email/templates/sample.txt b/notifications_consumer/processors/email/templates/sample.txt
deleted file mode 100644
index c1d1195..0000000
--- a/notifications_consumer/processors/email/templates/sample.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-Hello {{ name }},
-How are you?
-
-Cheers,
-{{ sender }}
diff --git a/notifications_consumer/processors/email/templates/simple_notification.html b/notifications_consumer/processors/email/templates/simple_notification.html
new file mode 100644
index 0000000..fb9ba45
--- /dev/null
+++ b/notifications_consumer/processors/email/templates/simple_notification.html
@@ -0,0 +1,47 @@
+<body>
+    <table align="center" border="0" cellpadding="0" cellspacing="0" width="100%"
+        style="margin-top: 20px; line-height: 1.7; color: #555;">
+        <tr>
+            <td>
+                <table align="center" border="0" cellpadding="0" cellspacing="0" width="100%"
+                    style="max-width: 660px; font-family: Helvetica, Arial, sans-serif; font-size: 14px; background: #ffffff;">
+                    <tr>
+                        <td style="border: 1px solid #ddd;">
+                            <table align="center" border="0" cellpadding="0" cellspacing="0" width="100%"
+                                style="border-collapse: collapse;">
+                                <tr>
+                                    <td>
+                                        <table border="0" cellpadding="0" cellspacing="0"
+                                            style="padding: 50px; text-align: center; margin: 0 auto">
+                                            <tr>
+                                                <td>
+                                                    <table border="0" cellpadding="0" cellspacing="0"
+                                                        style="padding: 20px; border-radius: 5px; background: #f9f9f9; min-width: 550px;">
+                                                        <tr>
+                                                            <td>
+                                                                <p>
+                                                                    {{ message_body|safe }}
+                                                                </p>
+                                                            </td>
+                                                        </tr>
+                                                    </table>
+                                                </td>
+                                            </tr>
+                                        </table>
+                                    </td>
+                                </tr>
+                            </table>
+                        </td>
+                    </tr>
+                    <tr>
+                        <td style="text-align: center; color: #aaa; font-size: 11px; padding-bottom: 10px;">
+                            <p style="padding: 10px;">
+                                This notification has been sent by the {{ sender }}.
+                            </p>
+                        </td>
+                    </tr>
+                </table>
+            </td>
+        </tr>
+    </table>
+</body>
diff --git a/notifications_consumer/processors/email/templates/simple_notification.txt b/notifications_consumer/processors/email/templates/simple_notification.txt
new file mode 100644
index 0000000..3f9532d
--- /dev/null
+++ b/notifications_consumer/processors/email/templates/simple_notification.txt
@@ -0,0 +1,4 @@
+{{ message_body }}
+
+-----
+This notification has been sent by the {{ sender }}.
diff --git a/notifications_consumer/processors/email/utils.py b/notifications_consumer/processors/email/utils.py
index 9fb7519..e835320 100644
--- a/notifications_consumer/processors/email/utils.py
+++ b/notifications_consumer/processors/email/utils.py
@@ -1,4 +1,5 @@
 """Email notifications utils."""
+import re
 from typing import Dict, List
 
 from jinja2 import Template
@@ -9,8 +10,6 @@ from vendor.django_mail.message import EmailMessage, EmailMultiAlternatives
 
 
 def create_email(
-    sender_name: str,
-    sender_email: str,
     recipient_emails: List[str],
     subject: str,
     text_template: Template,
@@ -19,17 +18,17 @@ def create_email(
     attachments: List,
 ):
     """Create EmailMultiAlternatives object to be sent."""
-    text_content = text_template.render(**context)
+    text_content = re.sub(re.compile("<.*?>"), "", text_template.render(**context))
     html_content = html_template.render(**context)
     noreply_email = Config.NOREPLY_ADDRESS
-    sender_name = sender_name.replace('"', "")
+    sender_name = context.get("sender")
     from_email = f"{sender_name} <{noreply_email}>"
     msg = EmailMultiAlternatives(
         subject=subject,
         body=text_content,
         from_email=from_email,
         to=recipient_emails,
-        reply_to=([sender_email] if sender_email else None),
+        reply_to=None,
         attachments=attachments,
     )
     msg.attach_alternative(html_content, "text/html")
diff --git a/scripts/docker-send-email.py b/scripts/docker-send-email.py
index 1f79a1c..b445ed5 100644
--- a/scripts/docker-send-email.py
+++ b/scripts/docker-send-email.py
@@ -4,7 +4,11 @@ import stomp
 
 conn = stomp.Connection([("activemq", 61613)])
 conn.connect("admin", "admin", wait=True)
-message_body = r"""{"message_body":"My message body","summary":"My summary","email":"test@cern.ch"}"""
+message_body = r"""{
+"message_body":"<p>Dear subscribers,</p>\n\n<p>This week news follows.&nbsp;</p>\n\n<p>&nbsp;</p>\n\n<p><strong>Topic 1</strong></p>\n\n<ul>\n\t<li>bla&nbsp;</li>\n\t<li>bla</li>\n\t<li>bla</li>\n</ul>\n\n<p>&nbsp;</p>\n\n<p><strong>Topic 2</strong></p>\n\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\n\n<p>&nbsp;</p>\n\n<p>See you next week,</p>\n\n<p>Myself.</p>\n",
+"summary":"This week news!",
+"email":"user@cern.ch"
+} """
 conn.send(
     body=message_body, destination="/queue/np.email", headers={"persistent": "true"}
 )
diff --git a/scripts/send-email-test-example.py b/scripts/send-email-test-example.py
index 9603dbe..6a57982 100644
--- a/scripts/send-email-test-example.py
+++ b/scripts/send-email-test-example.py
@@ -12,8 +12,8 @@ def main():
     subject = "This is a test subject"
     context = {"name": "Carina Antunes", "sender": sender_name}
 
-    text_template = Config.TEMPLATES.get_template("email/sample.txt")
-    html_template = Config.TEMPLATES.get_template("email/sample.html")
+    text_template = Config.TEMPLATES.get_template("email/simple_notification.txt")
+    html_template = Config.TEMPLATES.get_template("email/simple_notification.html")
     attachments = None
 
     email = create_email(
-- 
GitLab