Example #1
0
    def test_send_html(self):
        with self.settings(MAILER_EMAIL_BACKEND=
                           "django.core.mail.backends.locmem.EmailBackend"):
            mailer.send_html_mail("Subject",
                                  "Body",
                                  "<html><body>Body</body></html>",
                                  "*****@*****.**",
                                  ["*****@*****.**"],
                                  priority=PRIORITY_HIGH)

            # Ensure deferred was not deleted
            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 0)

            engine.send_all()

            self.assertEqual(len(mail.outbox), 1)
            sent = mail.outbox[0]

            # Default "plain text"
            self.assertEqual(sent.body, "Body")
            self.assertEqual(sent.content_subtype, "plain")

            # Alternative "text/html"
            self.assertEqual(sent.alternatives[0],
                             ("<html><body>Body</body></html>", "text/html"))
Example #2
0
 def test_mailer_use_file_lock_disabled(self):
     with self.settings(MAILER_USE_FILE_LOCK=False,
                        MAILER_EMAIL_BACKEND=
                        "django.core.mail.backends.locmem.EmailBackend"):
         engine.send_all()
     self.mock_acquire_lock.assert_not_called()
     self.mock_release_lock.assert_not_called()
Example #3
0
    def test_message_log(self):
        with self.settings(MAILER_EMAIL_BACKEND=
                           "django.core.mail.backends.locmem.EmailBackend"):
            mailer.send_mail("Subject Log", "Body", "*****@*****.**",
                             ["*****@*****.**"])

            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 0)
            self.assertEqual(MessageLog.objects.count(), 0)

            engine.send_all()

            self.assertEqual(Message.objects.count(), 0)
            self.assertEqual(Message.objects.deferred().count(), 0)
            self.assertEqual(MessageLog.objects.count(), 1)

            log = MessageLog.objects.all()[0]

            self.assertEqual(log.email.from_email, "*****@*****.**")
            self.assertEqual(log.to_addresses, ["*****@*****.**"])
            self.assertEqual(log.subject, "Subject Log")

            # Fake a log entry without email
            log.message_data = ""

            self.assertEqual(log.to_addresses, [])
            self.assertEqual(log.subject, "")
Example #4
0
 def handle(self, *args, **options):
     logger.info("-" * 72)
     # if PAUSE_SEND is turned on don't do anything.
     if not PAUSE_SEND:
         send_all()
     else:
         logger.info("sending is paused, quitting.")
Example #5
0
    def test_blacklisted_emails(self):
        with self.settings(MAILER_EMAIL_BACKEND=
                           "django.core.mail.backends.locmem.EmailBackend"):
            now = datetime_now()
            obj = DontSendEntry.objects.create(to_address="*****@*****.**",
                                               when_added=now)
            self.assertTrue(obj.to_address, "*****@*****.**")

            mailer.send_mail("Subject", "GoBody", "*****@*****.**",
                             ["*****@*****.**"])
            mailer.send_mail("Subject", "NoGoBody", "*****@*****.**",
                             ["*****@*****.**"])

            self.assertEqual(Message.objects.count(), 2)
            self.assertEqual(Message.objects.deferred().count(), 0)

            engine.send_all()

            # All messages are processed
            self.assertEqual(Message.objects.count(), 0)
            self.assertEqual(Message.objects.deferred().count(), 0)

            # but only one should get sent
            self.assertEqual(len(mail.outbox), 1)
            sent = mail.outbox[0]

            # Default "plain text"
            self.assertEqual(sent.body, "GoBody")
            self.assertEqual(sent.to, ["*****@*****.**"])
Example #6
0
    def test_message(self):
        with self.settings(MAILER_EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"):
            mailer.send_mail("Subject Msg", "Body", "*****@*****.**", ["*****@*****.**"])

            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 0)
            self.assertEqual(MessageLog.objects.count(), 0)

            msg = Message.objects.all()[0]

            self.assertEqual(msg.email.from_email, "*****@*****.**")
            self.assertEqual(msg.to_addresses, ["*****@*****.**"])
            self.assertEqual(msg.subject, "Subject Msg")

            # Fake a msg stored in DB with invalid data
            msg.message_data = ""

            self.assertEqual(msg.to_addresses, [])
            self.assertEqual(msg.subject, "")

            msg.save()

            with patch("logging.warning") as w:
                engine.send_all()

                w.assert_called_once()
                arg = w.call_args[0][0]
                self.assertIn("message discarded due to failure in converting from DB", arg)

            self.assertEqual(Message.objects.count(), 0)
            self.assertEqual(Message.objects.deferred().count(), 0)
            # Delivery should discard broken messages
            self.assertEqual(MessageLog.objects.count(), 0)
Example #7
0
    def test_throttling_delivery(self):
        TIME = 1  # throttle time = 1 second

        with self.settings(MAILER_EMAIL_BACKEND="mailer.tests.TestMailerEmailBackend"):
            # Calculate how long it takes to deliver 2 messages without throttling
            mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"])
            mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"])
            # 3 will be delivered, 2 remain deferred
            start_time = time.time()
            engine.send_all()
            unthrottled_time = time.time() - start_time

            self.assertEqual(len(TestMailerEmailBackend.outbox), 2)
            self.assertEqual(Message.objects.count(), 0)

        with self.settings(MAILER_EMAIL_BACKEND="mailer.tests.TestMailerEmailBackend", MAILER_EMAIL_THROTTLE=TIME):  # noqa
            mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"])
            mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"])
            # 3 will be delivered, 2 remain deferred
            start_time = time.time()
            engine.send_all()
            throttled_time = time.time() - start_time

            self.assertEqual(len(TestMailerEmailBackend.outbox), 2)
            self.assertEqual(Message.objects.count(), 0)

        # NOTE This is a bit tricky to test due to possible fluctuations on
        # execution time. Test may randomly fail
        # NOTE 2*TIME because 2 emails are sent during the test
        self.assertAlmostEqual(unthrottled_time, throttled_time - 2*TIME, places=1)
Example #8
0
    def test_resend(self):
        # Test resend enables queue
        with self.settings(MAILER_EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"):
            q = Queue.objects.create(pk=1, name="test", mail_enabled=False)
            q1 = Queue.objects.create(pk=2, name="test1", mail_enabled=True)

            mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"], queue=1)
            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.filter(queue=q).count(), 1)

            mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"], queue=2)
            self.assertEqual(Message.objects.count(), 2)
            self.assertEqual(Message.objects.filter(queue=q1).count(), 1)

            engine.send_all()

            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 1)
            self.assertEqual(MessageLog.objects.count(), 1)

            date = datetime.datetime.now() - datetime.timedelta(minutes=15)
            engine.resend(['test'], date.strftime("%Y-%m-%d %H:%M"))

            q = Queue.objects.get(pk=1)

            self.assertEqual(q.mail_enabled, True)
            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.filter(queue=q).count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 0)
Example #9
0
    def test_blacklisted_emails(self):
        with self.settings(MAILER_EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"):
            now = datetime_now()
            obj = DontSendEntry.objects.create(to_address="*****@*****.**", when_added=now)
            self.assertTrue(obj.to_address, "*****@*****.**")

            mailer.send_mail("Subject", "GoBody", "*****@*****.**", ["*****@*****.**"])
            mailer.send_mail("Subject", "NoGoBody", "*****@*****.**", ["*****@*****.**"])

            self.assertEqual(Message.objects.count(), 2)
            self.assertEqual(Message.objects.deferred().count(), 0)

            engine.send_all()

            # All messages are processed
            self.assertEqual(Message.objects.count(), 0)
            self.assertEqual(Message.objects.deferred().count(), 0)

            # but only one should get sent
            self.assertEqual(len(mail.outbox), 1)
            sent = mail.outbox[0]

            # Default "plain text"
            self.assertEqual(sent.body, "GoBody")
            self.assertEqual(sent.to, ["*****@*****.**"])
Example #10
0
    def test_message_log(self):
        with self.settings(MAILER_EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"):
            mailer.send_mail("Subject Log", "Body", "*****@*****.**", ["*****@*****.**"])

            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 0)
            self.assertEqual(MessageLog.objects.count(), 0)

            engine.send_all()

            self.assertEqual(Message.objects.count(), 0)
            self.assertEqual(Message.objects.deferred().count(), 0)
            self.assertEqual(MessageLog.objects.count(), 1)

            log = MessageLog.objects.all()[0]

            self.assertEqual(log.email.from_email, "*****@*****.**")
            self.assertEqual(log.to_addresses, ["*****@*****.**"])
            self.assertEqual(log.subject, "Subject Log")

            # Fake a log entry without email
            log.message_data = ""

            self.assertEqual(log.to_addresses, [])
            self.assertEqual(log.subject, "")
Example #11
0
    def test_message(self):
        with self.settings(MAILER_EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"):
            mailer.send_mail("Subject Msg", "Body", "*****@*****.**", ["*****@*****.**"])

            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 0)
            self.assertEqual(MessageLog.objects.count(), 0)

            msg = Message.objects.all()[0]

            self.assertEqual(msg.email.from_email, "*****@*****.**")
            self.assertEqual(msg.to_addresses, ["*****@*****.**"])
            self.assertEqual(msg.subject, "Subject Msg")

            # Fake a msg stored in DB with invalid data
            msg.message_data = ""

            self.assertEqual(msg.to_addresses, [])
            self.assertEqual(msg.subject, "")

            msg.save()

            with patch("logging.warning") as w:
                engine.send_all()

                w.assert_called_once()
                arg = w.call_args[0][0]
                self.assertIn("message discarded due to failure in converting from DB", arg)

            self.assertEqual(Message.objects.count(), 0)
            self.assertEqual(Message.objects.deferred().count(), 0)
            # Delivery should discard broken messages
            self.assertEqual(MessageLog.objects.count(), 0)
Example #12
0
    def test_message(self):
        with self.settings(MAILER_EMAIL_BACKEND=
                           "django.core.mail.backends.locmem.EmailBackend"):
            mailer.send_mail("Subject Msg", "Body", "*****@*****.**",
                             ["*****@*****.**"])

            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 0)
            self.assertEqual(MessageLog.objects.count(), 0)

            msg = Message.objects.all()[0]

            self.assertEqual(msg.email.from_email, "*****@*****.**")
            self.assertEqual(msg.to_addresses, ["*****@*****.**"])
            self.assertEqual(msg.subject, "Subject Msg")

            # Fake a msg stored in DB with invalid data
            msg.message_data = ""

            self.assertEqual(msg.to_addresses, [])
            self.assertEqual(msg.subject, "")

            msg.save()

            engine.send_all()

            self.assertEqual(Message.objects.count(), 0)
            self.assertEqual(Message.objects.deferred().count(), 0)
            # Delivery should discard broken messages
            self.assertEqual(MessageLog.objects.count(), 0)
Example #13
0
    def test_send_mass_mail(self):
        with self.settings(MAILER_EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"):
            mails = (
                ("Subject ☺", "Body", "*****@*****.**", ["*****@*****.**"]),
                ("Subject ☺", "Body", "*****@*****.**", ["*****@*****.**"]),
                ("Subject ☺", "Body", "*****@*****.**", ["*****@*****.**"]),
                ("Subject ☺", "Body", "*****@*****.**", ["*****@*****.**"]),
            )

            mailer.send_mass_mail(mails)

            self.assertEqual(Message.objects.count(), 4)
            self.assertEqual(Message.objects.deferred().count(), 0)

            engine.send_all()

            self.assertEqual(Message.objects.count(), 0)
            self.assertEqual(Message.objects.deferred().count(), 0)

            self.assertEqual(len(mail.outbox), 4)
            for i, sent in enumerate(mail.outbox):
                # Default "plain text"
                self.assertEqual(sent.subject, "Subject ☺")
                self.assertEqual(sent.from_email, "mass{0}@example.com".format(i))
                self.assertEqual(sent.to, ["recipient{0}@example.com".format(i)])
Example #14
0
    def test_message(self):
        with self.settings(MAILER_EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"):
            mailer.send_mail("Subject Msg", "Body", "*****@*****.**", ["*****@*****.**"])

            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 0)
            self.assertEqual(MessageLog.objects.count(), 0)

            msg = Message.objects.all()[0]

            self.assertEqual(msg.email.from_email, "*****@*****.**")
            self.assertEqual(msg.to_addresses, ["*****@*****.**"])
            self.assertEqual(msg.subject, "Subject Msg")

            # Fake a msg stored in DB with invalid data
            msg.message_data = ""

            self.assertEqual(msg.to_addresses, [])
            self.assertEqual(msg.subject, "")

            msg.save()

            engine.send_all()

            self.assertEqual(Message.objects.count(), 0)
            self.assertEqual(Message.objects.deferred().count(), 0)
            # Delivery should discard broken messages
            self.assertEqual(MessageLog.objects.count(), 0)
Example #15
0
    def test_send_mass_mail(self):
        with self.settings(MAILER_EMAIL_BACKEND=
                           "django.core.mail.backends.locmem.EmailBackend"):
            mails = (
                ("Subject", "Body", "*****@*****.**",
                 ["*****@*****.**"]),
                ("Subject", "Body", "*****@*****.**",
                 ["*****@*****.**"]),
                ("Subject", "Body", "*****@*****.**",
                 ["*****@*****.**"]),
                ("Subject", "Body", "*****@*****.**",
                 ["*****@*****.**"]),
            )

            mailer.send_mass_mail(mails)

            self.assertEqual(Message.objects.count(), 4)
            self.assertEqual(Message.objects.deferred().count(), 0)

            engine.send_all()

            self.assertEqual(Message.objects.count(), 0)
            self.assertEqual(Message.objects.deferred().count(), 0)

            self.assertEqual(len(mail.outbox), 4)
            for i, sent in enumerate(mail.outbox):
                # Default "plain text"
                self.assertEqual(sent.from_email,
                                 "mass{0}@example.com".format(i))
                self.assertEqual(sent.to,
                                 ["recipient{0}@example.com".format(i)])
Example #16
0
 def handle_noargs(self, **options):
     logging.basicConfig(level=logging.DEBUG, format="%(message)s")
     logging.info("-" * 72)
     # if PAUSE_SEND is turned on don't do anything.
     if not PAUSE_SEND:
         send_all()
     else:
         logging.info("sending is paused, quitting.")
Example #17
0
 def handle(self, **kwargs):
     logging.basicConfig(level=logging.DEBUG, format="%(message)s")
     logging.info("-" * 72)
     # if PAUSE_SEND is turned on don't do anything.
     if not PAUSE_SEND:
         send_all()
     else:
         logging.info("sending is paused, quitting.")
Example #18
0
    def test_loop_detection(self):
        with self.settings(EMAIL_BACKEND='mailer.backend.DbBackend',
                           MAILER_EMAIL_BACKEND='mailer.backend.DbBackend'), \
                self.assertRaises(ImproperlyConfigured) as catcher:
            engine.send_all()

        self.assertIn('mailer.backend.DbBackend', str(catcher.exception))
        self.assertIn('EMAIL_BACKEND', str(catcher.exception))
        self.assertIn('MAILER_EMAIL_BACKEND', str(catcher.exception))
Example #19
0
 def send_mail(success):
     backend = ("django.core.mail.backends.locmem.EmailBackend"
                if success else "tests.FailingMailerEmailBackend")
     with self.settings(MAILER_EMAIL_BACKEND=backend):
         mailer.send_mail("Subject", "Body", "*****@*****.**",
                          ["*****@*****.**"])
         engine.send_all()
         if not success:
             Message.objects.retry_deferred()
             engine.send_all()
Example #20
0
 def send_emails(*args, **kwargs):
     """
     Sends  queued emails
     """
     try:
         from mailer.engine import send_all
         send_all()
         logger.info("send_all()")
     except exc as Exception:
         logger.error(exc)
Example #21
0
 def test_control_max_delivery_amount(self):
     with self.settings(MAILER_EMAIL_BACKEND="mailer.tests.TestMailerEmailBackend", MAILER_EMAIL_MAX_BATCH=2):  # noqa
         mailer.send_mail("Subject1", "Body1", "*****@*****.**", ["*****@*****.**"])
         mailer.send_mail("Subject2", "Body2", "*****@*****.**", ["*****@*****.**"])
         mailer.send_mail("Subject3", "Body3", "*****@*****.**", ["*****@*****.**"])
         self.assertEqual(Message.objects.count(), 3)
         self.assertEqual(len(TestMailerEmailBackend.outbox), 0)
         engine.send_all()
         self.assertEqual(len(TestMailerEmailBackend.outbox), 2)
         self.assertEqual(Message.objects.count(), 1)
         self.assertEqual(MessageLog.objects.count(), 2)
Example #22
0
 def test_save_changes_to_email(self):
     """
     Test that changes made to the email by the backend are
     saved in MessageLog.
     """
     with self.settings(MAILER_EMAIL_BACKEND="mailer.tests.TestMailerEmailBackend"):
         mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"])
         engine.send_all()
         m = MessageLog.objects.get()
         self.assertEqual(m.email.extra_headers['X-Sent-By'],
                          'django-mailer-tests')
Example #23
0
 def handle(self, *args, **options):
     if options['cron'] == 0:
         logging.basicConfig(level=logging.DEBUG, format="%(message)s")
     else:
         logging.basicConfig(level=logging.ERROR, format="%(message)s")
     logging.info("-" * 72)
     # if PAUSE_SEND is turned on don't do anything.
     if not PAUSE_SEND:
         send_all()
     else:
         logging.info("sending is paused, quitting.")
Example #24
0
 def test_set_and_save_message_id(self):
     """
     Test that message-id is set and saved correctly
     """
     with self.settings(
             MAILER_EMAIL_BACKEND="tests.TestMailerEmailBackend"):
         mailer.send_mail("Subject", "Body", "*****@*****.**",
                          ["*****@*****.**"])
         engine.send_all()
         m = MessageLog.objects.get()
         self.assertEqual(m.email.extra_headers['Message-ID'], m.message_id)
Example #25
0
 def test_control_max_delivery_amount(self):
     with self.settings(MAILER_EMAIL_BACKEND="mailer.tests.TestMailerEmailBackend", MAILER_EMAIL_MAX_BATCH=2):  # noqa
         mailer.send_mail("Subject1", "Body1", "*****@*****.**", ["*****@*****.**"])
         mailer.send_mail("Subject2", "Body2", "*****@*****.**", ["*****@*****.**"])
         mailer.send_mail("Subject3", "Body3", "*****@*****.**", ["*****@*****.**"])
         self.assertEqual(Message.objects.count(), 3)
         self.assertEqual(len(TestMailerEmailBackend.outbox), 0)
         engine.send_all()
         self.assertEqual(len(TestMailerEmailBackend.outbox), 2)
         self.assertEqual(Message.objects.count(), 1)
         self.assertEqual(MessageLog.objects.count(), 2)
Example #26
0
def sendmail_pending(*args, **kwargs):
    """A periodic task that send pending mail

    **Usage**:

        sendmail_pending.delay()
    """
    logger.info("TASK :: sendmail_pending")
    if not PAUSE_SEND:
        send_all()
    else:
        logger.info("Sending mail is paused.")
Example #27
0
 def handle(self, *args, **options):
     if options['cron'] == 0:
         logging.basicConfig(level=logging.DEBUG, format="%(message)s")
     else:
         logging.basicConfig(level=logging.ERROR, format="%(message)s")
     logging.info("-" * 72)
     # if PAUSE_SEND is turned on don't do anything.
     if not PAUSE_SEND:
         send_all()
     else:
         logging.info("sending is paused, quitting.")
     connection.close()
Example #28
0
 def test_set_and_save_message_id(self):
     """
     Test that message-id is set and saved correctly
     """
     with self.settings(MAILER_EMAIL_BACKEND="mailer.tests.TestMailerEmailBackend"):
         mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"])
         engine.send_all()
         m = MessageLog.objects.get()
         self.assertEqual(
             m.email.extra_headers['Message-ID'],
             m.message_id
         )
Example #29
0
 def handle(self, *args, **options):
     if options['cron'] == 0:
         warnings.warn(
             "send_mail's -c/--cron option is no longer "
             "necessary and will be removed in a future release",
             DeprecationWarning)
     logger.info("-" * 72)
     # if PAUSE_SEND is turned on don't do anything.
     if not PAUSE_SEND:
         send_all()
     else:
         logger.info("sending is paused, quitting.")
Example #30
0
def sendmail_pending(*args, **kwargs):
    """A periodic task that send pending mail

    **Usage**:

        sendmail_pending.delay()
    """
    logger.info("TASK :: sendmail_pending")
    if not PAUSE_SEND:
        send_all()
    else:
        logger.info("Sending mail is paused.")
Example #31
0
 def handle_noargs(self, **options):
     log_levels = {
         '0': logging.WARNING,
         '1': logging.INFO,
         '2': logging.DEBUG,
     }
     level = log_levels[options['verbosity']]
     logging.basicConfig(level=level, format="%(message)s")
     # if PAUSE_SEND is turned on don't do anything.
     if not PAUSE_SEND:
         send_all()
     else:
         logging.info("sending is paused, quitting.")
Example #32
0
 def test_save_changes_to_email(self):
     """
     Test that changes made to the email by the backend are
     saved in MessageLog.
     """
     with self.settings(
             MAILER_EMAIL_BACKEND="tests.TestMailerEmailBackend"):
         mailer.send_mail("Subject", "Body", "*****@*****.**",
                          ["*****@*****.**"])
         engine.send_all()
         m = MessageLog.objects.get()
         self.assertEqual(m.email.extra_headers['X-Sent-By'],
                          'django-mailer-tests')
Example #33
0
 def handle_noargs(self, **options):
     log_levels = {
         '0': logging.WARNING,
         '1': logging.INFO,
         '2': logging.DEBUG,
     }
     level = log_levels[options['verbosity']]
     logging.basicConfig(level=level, format="%(message)s")
     # if PAUSE_SEND is turned on don't do anything.
     if not PAUSE_SEND:
         send_all()
     else:
         logging.info("sending is paused, quitting.")
Example #34
0
 def test_mailer_email_backend(self):
     """
     Test that calling "manage.py send_mail" actually sends mail using the
     specified MAILER_EMAIL_BACKEND
     """
     with self.settings(MAILER_EMAIL_BACKEND="mailer.tests.TestMailerEmailBackend"):
         mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"])
         self.assertEqual(Message.objects.count(), 1)
         self.assertEqual(len(TestMailerEmailBackend.outbox), 0)
         engine.send_all()
         self.assertEqual(len(TestMailerEmailBackend.outbox), 1)
         self.assertEqual(Message.objects.count(), 0)
         self.assertEqual(MessageLog.objects.count(), 1)
Example #35
0
 def test_mailer_email_backend(self):
     """
     Test that calling "manage.py send_mail" actually sends mail using the
     specified MAILER_EMAIL_BACKEND
     """
     with self.settings(MAILER_EMAIL_BACKEND="mailer.tests.TestMailerEmailBackend"):
         mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"])
         self.assertEqual(Message.objects.count(), 1)
         self.assertEqual(len(TestMailerEmailBackend.outbox), 0)
         engine.send_all()
         self.assertEqual(len(TestMailerEmailBackend.outbox), 1)
         self.assertEqual(Message.objects.count(), 0)
         self.assertEqual(MessageLog.objects.count(), 1)
Example #36
0
 def test_verify_by_client(self):
     logged_in = self.client.login(username='******', password='******')
     self.assertTrue(logged_in)
     create_email = self.client.post('/account/email/', {'email':'*****@*****.**', 'action':'add'})
     # email_confirmation usees the mailer app if its installed, so 
     # make sure queue is cleared
     if 'mailer' in settings.INSTALLED_APPS:
         engine.send_all()
     self.assertEquals(1, len(mail.outbox))
     confirmation_link = re.search(r'http\S*/', mail.outbox[0].body).group(0)
     self.client.get(confirmation_link[len('http://testserver'):])
     # email should be set
     self.bob = User.objects.get(username='******')
     self.assertEquals(self.bob.email, '*****@*****.**')
Example #37
0
    def test_sending_extra_queue_disabled(self):
        # Test messages don't get sent that are in a disabled queue
        with self.settings(MAILER_EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"):
            Queue.objects.create(pk=1, name="test", mail_enabled=False)

            mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"], queue=1)
            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 0)

            engine.send_all()

            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 1)
            self.assertEqual(MessageLog.objects.count(), 0)
    def handle(self, **options):
        quiet = options.get('quiet', False)

        # Set logging level if quiet
        if quiet:
            logging.disable(logging.INFO)

        logging.basicConfig(level=logging.DEBUG, format="%(message)s")
        logging.info("-" * 72)
        # if PAUSE_SEND is turned on don't do anything.
        if not PAUSE_SEND:
            send_all()
        else:
            logging.info("sending is paused, quitting.")
Example #39
0
    def test_message_log_str(self):
        with self.settings(MAILER_EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"):
            mailer.send_mail("Subject Log", "Body", "*****@*****.**", ["*****@*****.**"])
            engine.send_all()

            self.assertEqual(MessageLog.objects.count(), 1)

            log = MessageLog.objects.get()
            self.assertEqual(
                str(log),
                'On {0}, \"Subject Log\" to [email protected]'.format(log.when_attempted),
            )
            log.message_data = None
            self.assertEqual(str(log), '<MessageLog repr unavailable>')
    def handle(self, **options):
        quiet = options.get('quiet', False)

        # Set logging level if quiet
        if quiet:
            logging.disable(logging.INFO)

        logging.basicConfig(level=logging.DEBUG, format="%(message)s")
        logging.info("-" * 72)
        # if PAUSE_SEND is turned on don't do anything.
        if not PAUSE_SEND:
            send_all()
        else:
            logging.info("sending is paused, quitting.")
Example #41
0
 def test_verify_by_client(self):
     logged_in = self.client.login(username='******', password='******')
     self.assertTrue(logged_in)
     create_email = self.client.post('/account/email/', {'email':'*****@*****.**', 'action':'add'})
     # email_confirmation usees the mailer app if its installed, so 
     # make sure queue is cleared
     if 'mailer' in settings.INSTALLED_APPS:
         engine.send_all()
     self.assertEquals(1, len(mail.outbox))
     confirmation_link = re.search(r'http\S*/', mail.outbox[0].body).group(0)
     self.client.get(confirmation_link[len('http://testserver'):])
     # email should be set
     self.bob = User.objects.get(username='******')
     self.assertEquals(self.bob.email, '*****@*****.**')
Example #42
0
 def test_mailer_email_backend(self):
     """
     Test that calling "manage.py send_mail" actually sends mail using the specified MAILER_EMAIL_BACKEND
     """
     global sent_messages
     from mailer import send_mail
     with self.settings(MAILER_EMAIL_BACKEND="mailer.tests.TestMailerEmailBackend"):
         send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"])
         self.assertEqual(Message.objects.count(), 1)
         self.assertEqual(len(sent_messages), 0)
         from mailer.engine import send_all
         send_all()
         self.assertEqual(len(sent_messages), 1)
         self.assertEqual(Message.objects.count(), 0)
         self.assertEqual(MessageLog.objects.count(), 1)
Example #43
0
    def test_throttling_delivery(self):
        TIME = 1  # throttle time = 1 second

        with self.settings(MAILER_EMAIL_BACKEND="mailer.tests.TestMailerEmailBackend", MAILER_EMAIL_THROTTLE=TIME):  # noqa
            mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"])
            mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"])
            start_time = time.time()
            engine.send_all()
            throttled_time = time.time() - start_time

            self.assertEqual(len(TestMailerEmailBackend.outbox), 2)
            self.assertEqual(Message.objects.count(), 0)

        # Notes: 2 * TIME because 2 emails are sent during the test
        self.assertGreater(throttled_time, 2 * TIME)
Example #44
0
    def test_throttling_delivery(self):
        TIME = 1  # throttle time = 1 second

        with self.settings(MAILER_EMAIL_BACKEND="mailer.tests.TestMailerEmailBackend", MAILER_EMAIL_THROTTLE=TIME):  # noqa
            mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"])
            mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"])
            start_time = time.time()
            engine.send_all()
            throttled_time = time.time() - start_time

            self.assertEqual(len(TestMailerEmailBackend.outbox), 2)
            self.assertEqual(Message.objects.count(), 0)

        # Notes: 2 * TIME because 2 emails are sent during the test
        self.assertGreater(throttled_time, 2 * TIME)
Example #45
0
    def handle(self, *args, **options):

        template_name = options['template']
        group_name = options['name']
        subject = options['subject']
        from_email = options['from'] or settings.ADMINS[0][1]

        group = models.EmailGroup.objects.filter(name=group_name).first()
        # Sender requires a list.
        if not group:
            logger.error(f"group.name={group_name} does not exist.")
            return

        # Get the recipients.
        recipients = [
            person.address.email for person in group.subscription_set.all()
        ]

        logger.info(f"Email list size: {len(recipients)}")

        # Test the templates
        if os.path.isfile(template_name):
            logger.error(f"Missing template: {template_name}")
            return

        # Generate emails.
        logger.info(
            f"Emails from={from_email} to group.name={group.name} using template:{template_name}"
        )

        # The object that parsers the template.
        email = sender.EmailTemplate(template_name)

        # This is the context passed to each template.
        site = Site.objects.get_current()

        # Accumulate the emails into the database.
        for address in recipients:
            context = dict(site=site,
                           protocol=settings.PROTOCOL,
                           subject=subject)
            email.send(context=context,
                       from_email=from_email,
                       recipient_list=[address])

        # Send the emails.
        send_all()
        logger.info("Emails have been sent")
    def handle(self, *args, **options):
        logging.basicConfig(level=logging.DEBUG, format="%(message)s")
        logging.info("-" * 72)
        # if PAUSE_SEND is turned on don't do anything.
        limit = int(args[0])

        try:
            throttle = float(args[1])
        except IndexError:
            throttle = 0

        if not PAUSE_SEND:
            logging.info("Sending %d emails at" % limit)
            send_all(limit, throttle)
        else:
            logging.info("sending is paused, quitting.")
Example #47
0
 def test_mailer_email_backend(self):
     """
     Test that calling "manage.py send_mail" actually sends mail using the
     specified MAILER_EMAIL_BACKEND
     """
     with self.settings(MAILER_EMAIL_BACKEND="mailer.tests.TestMailerEmailBackend"):
         mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"])
         self.assertEqual(Message.objects.count(), 1)
         self.assertEqual(len(TestMailerEmailBackend.outbox), 0)
         engine.send_all()
         self.assertEqual(len(TestMailerEmailBackend.outbox), 1)
         self.assertEqual(Message.objects.count(), 0)
         self.assertEqual(MessageLog.objects.count(), 1)
         with patch.object(mailer.models, 'datetime_now') as datetime_now_patch:
             datetime_now_patch.side_effect = lambda: datetime_now() + datetime.timedelta(days=2)
             self.assertEqual(MessageLog.objects.purge_old_entries(1), 1)
         self.assertEqual(MessageLog.objects.count(), 0)
Example #48
0
 def handle(self, **options):
     delay = float(options.get('delay', 3))
     max_time = float(options.get('max_time', 60))
     logging.basicConfig(level=logging.DEBUG, format="%(message)s")
     logging.info("-" * 72)
     # if PAUSE_SEND is turned on don't do anything.
     start = time()
     while True:
         if not PAUSE_SEND:
             send_all()
         else:
             logging.info("sending is paused, quitting.")
         if time() - start > max_time - delay:
             logging.info("done, leave...")
             break
         logging.info("waiting %.2f seconds to send next." % delay)
         sleep(delay)
Example #49
0
def send_all():
    """
    Needed when the email backend is django-mailer to send queued emails.
    """

    # No email sending during data migration.
    if settings.DATA_MIGRATION:
        return

    # Queued email exists only when the backend is the django-mailer.
    if settings.EMAIL_BACKEND == "mailer.backend.DbBackend":
        try:
            from mailer import engine
            logger.info(f"sending queued emails")
            engine.send_all()
        except Exception as exc:
            logger.error(f"send_all() error: {exc}")
Example #50
0
 def test_mailer_email_backend(self):
     """
     Test that calling "manage.py send_mail" actually sends mail using the specified MAILER_EMAIL_BACKEND
     """
     global sent_messages
     from mailer import send_mail
     with self.settings(
             MAILER_EMAIL_BACKEND="mailer.tests.TestMailerEmailBackend"):
         send_mail("Subject", "Body", "*****@*****.**",
                   ["*****@*****.**"])
         self.assertEqual(Message.objects.count(), 1)
         self.assertEqual(len(sent_messages), 0)
         from mailer.engine import send_all
         send_all()
         self.assertEqual(len(sent_messages), 1)
         self.assertEqual(Message.objects.count(), 0)
         self.assertEqual(MessageLog.objects.count(), 1)
Example #51
0
    def test_message_log_str(self):
        with self.settings(MAILER_EMAIL_BACKEND=
                           "django.core.mail.backends.locmem.EmailBackend"):
            mailer.send_mail("Subject Log", "Body", "*****@*****.**",
                             ["*****@*****.**"])
            engine.send_all()

            self.assertEqual(MessageLog.objects.count(), 1)

            log = MessageLog.objects.get()
            self.assertEqual(
                str(log),
                'On {0}, \"Subject Log\" to [email protected]'.format(
                    log.when_attempted),
            )
            log.message_data = None
            self.assertEqual(str(log), '<MessageLog repr unavailable>')
Example #52
0
    def test_mail_managers(self):
        with self.settings(MAILER_EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend", MANAGERS=(("Test", "*****@*****.**"),)):  # noqa
            mailer.mail_managers("Subject", "Manager Body")

            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 0)

            engine.send_all()

            self.assertEqual(Message.objects.count(), 0)
            self.assertEqual(Message.objects.deferred().count(), 0)

            self.assertEqual(len(mail.outbox), 1)
            sent = mail.outbox[0]

            # Default "plain text"
            self.assertEqual(sent.body, "Manager Body")
            self.assertEqual(sent.to, ["*****@*****.**"])
Example #53
0
    def test_mail_managers(self):
        with self.settings(MAILER_EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend", MANAGERS=(("Test", "*****@*****.**"),)):  # noqa
            mailer.mail_managers("Subject", "Manager Body")

            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 0)

            engine.send_all()

            self.assertEqual(Message.objects.count(), 0)
            self.assertEqual(Message.objects.deferred().count(), 0)

            self.assertEqual(len(mail.outbox), 1)
            sent = mail.outbox[0]

            # Default "plain text"
            self.assertEqual(sent.body, "Manager Body")
            self.assertEqual(sent.to, ["*****@*****.**"])
Example #54
0
    def test_retry_deferred(self):
        with self.settings(MAILER_EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"):
            q = Queue.objects.get(pk=0)
            q.mail_enabled = False
            q.save()

            mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"], queue=0)

            engine.send_all()

            self.assertEqual(Message.objects.deferred().count(), 1)

            q.mail_enabled = True
            q.save()

            call_command('retry_deferred')

            self.assertEqual(Message.objects.deferred().count(), 0)
Example #55
0
def send_email(template_name,
               email_list,
               extra_context={},
               from_email=None,
               subject="Subject",
               send=False):

    from_email = from_email or settings.ADMINS[0][1]

    # Test the templates exists
    if os.path.isfile(template_name):
        logger.error(f"Missing template: {template_name}")
        return False
    try:
        # Generate emails.
        logger.debug(
            f"Emails from={from_email} to email_list={email_list} using template:{template_name}"
        )

        # The object that parsers the template.
        email = sender.EmailTemplate(template_name)

        # Accumulate the emails into the database.
        context = dict(domain=settings.SITE_DOMAIN,
                       protocol=settings.PROTOCOL,
                       port=settings.HTTP_PORT,
                       subject=subject,
                       name=settings.SITE_NAME)
        context.update(extra_context)
        email.send(context=context,
                   from_email=from_email,
                   recipient_list=email_list)

        if send and email_list:
            # Send the emails.
            send_all()
            logging.info(
                f"Email has been sent to { len(email_list) } accounts.")

    except Exception as exc:
        logger.error(f"Mailing error : {exc}")
        return False

    return True
Example #56
0
    def test_multiple_queues(self):
        # Test sending on both an enabled and a disabled queue, ensure only one gets sent
        with self.settings(MAILER_EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"):
            q = Queue.objects.create(pk=1, name="test", mail_enabled=False)
            q1 = Queue.objects.create(pk=2, name="test1", mail_enabled=True)

            mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"], queue=1)
            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.filter(queue=q).count(), 1)

            mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"], queue=2)
            self.assertEqual(Message.objects.count(), 2)
            self.assertEqual(Message.objects.filter(queue=q1).count(), 1)

            engine.send_all()

            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 1)
            self.assertEqual(MessageLog.objects.count(), 1)
Example #57
0
def notify(template_name,
           email_list,
           extra_context={},
           from_email=None,
           subject="Subject",
           send=False):

    from_email = from_email or settings.ADMINS[0][1]

    # Test the templates exists
    if os.path.isfile(template_name):
        logger.error(f"Missing template: {template_name}")
        return False
    try:
        # Generate emails.
        logger.info(
            f"Emails from={from_email} to email_list={email_list} using template:{template_name}"
        )

        # The object that parsers the template.
        email = sender.EmailTemplate(template_name)

        # This is the context passed to each template.
        site = Site.objects.get_current()

        # Accumulate the emails into the database.
        context = dict(site=site, protocol=settings.PROTOCOL, subject=subject)
        context.update(extra_context)
        email.send(context=context,
                   from_email=from_email,
                   recipient_list=email_list)

        if send and email_list:
            # Send the emails.
            send_all()
            logger.info("Emails have been sent")

    except Exception as exc:
        logger.error(f"Mailing error : {exc}")
        return False

    return True
Example #58
0
 def test_mailer_email_backend(self):
     """
     Test that calling "manage.py send_mail" actually sends mail using the specified MAILER_EMAIL_BACKEND
     """
     global sent_messages
     from mailer import send_mail
     with self.settings(MAILER_EMAIL_BACKEND="mailer.tests.TestMailerEmailBackend"):
         send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"], priority="medium")
         self.assertEqual(Message.objects.count(), 1)
         msg_obj = Message.objects.all()[0]
         self.assertEqual(msg_obj.status, STATUS_PENDING)
         self.assertEqual(msg_obj.priority, 2)
         self.assertEqual(len(sent_messages), 0)
         from mailer.engine import send_all
         send_all()
         self.assertEqual(len(sent_messages), 1)
         self.assertEqual(Message.objects.count(), 1)
         msg_obj = Message.objects.all()[0]
         self.assertEqual(msg_obj.status, STATUS_SENT)
         self.assertEqual(msg_obj.priority, 2)
Example #59
0
    def test_send_html(self):
        with self.settings(MAILER_EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"):
            mailer.send_html_mail("Subject", "Body", "<html><body>Body</body></html>",
                                  "*****@*****.**", ["*****@*****.**"], "high")

            # Ensure deferred was not deleted
            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 0)

            engine.send_all()

            self.assertEqual(len(mail.outbox), 1)
            sent = mail.outbox[0]

            # Default "plain text"
            self.assertEqual(sent.body, "Body")
            self.assertEqual(sent.content_subtype, "plain")

            # Alternative "text/html"
            self.assertEqual(sent.alternatives[0],
                             ("<html><body>Body</body></html>", "text/html"))
Example #60
0
    def test_retry_deferred(self):
        with self.settings(MAILER_EMAIL_BACKEND="mailer.tests.FailingMailerEmailBackend"):
            mailer.send_mail("Subject", "Body", "*****@*****.**", ["*****@*****.**"])
            engine.send_all()
            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 1)
            self.assertEqual(MessageLog.objects.count(), 1)
            with patch.object(mailer.models, 'datetime_now') as datetime_now_patch:
                datetime_now_patch.side_effect = lambda: datetime_now() + datetime.timedelta(days=2)
                self.assertEquals(MessageLog.objects.purge_old_entries(1), 0)
                call_command('purge_mail_log', '1')
            self.assertEqual(MessageLog.objects.count(), 1)

        with self.settings(MAILER_EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend"):

            engine.send_all()
            self.assertEqual(len(mail.outbox), 0)
            # Should not have sent the deferred ones
            self.assertEqual(Message.objects.count(), 1)
            self.assertEqual(Message.objects.deferred().count(), 1)

            # Now mark them for retrying
            Message.objects.retry_deferred()
            engine.send_all()
            self.assertEqual(len(mail.outbox), 1)
            self.assertEqual(Message.objects.count(), 0)