Пример #1
0
 def test_email_sends_unique_id(self):
     """
     Tests sending a ``SendGridEmailMessage`` adds a ``message_id`` to the unique args.
     """
     email = SendGridEmailMessage(to=TEST_RECIPIENTS, from_email=TEST_SENDER_EMAIL)
     email.send()
     self.assertTrue(email.sendgrid_headers.data["unique_args"]["message_id"])
Пример #2
0
    def test_send_with_unique_arguments(self):
        @receiver(sendgrid_email_sent)
        def receive_sendgrid_email_sent(*args, **kwargs):
            """
            Receives sendgrid_email_sent signals.
            """
            emailMessage = kwargs["message"]
            sendgridHeadersData = emailMessage.sendgrid_headers.data

            self.assertTrue(sendgridHeadersData["unique_args"])

        sendgridEmailMessage = SendGridEmailMessage(
            to=TEST_RECIPIENTS, from_email=TEST_SENDER_EMAIL)
        # sendgridEmailMessage.sendgrid_headers.setCategory(self.testCategoryNames[0])
        # sendgridEmailMessage.update_headers()
        sendgridEmailMessage.send()

        argument = self.assert_argument_exists("message_id")
        self.assertTrue(argument)

        expectedUniqueArgKeyValue = {
            "key": "message_id",
            "value": sendgridEmailMessage.message_id,
        }
        uniqueArgument = self.assert_unique_argument_exists(**expectedUniqueArgKeyValue)
        self.assertTrue(uniqueArgument)
Пример #3
0
    def setUp(self):
        emailMessage = SendGridEmailMessage(
            to=TEST_RECIPIENTS,
            from_email=TEST_SENDER_EMAIL)

        response = emailMessage.send()
        self.assertEqual(response, 1)
        self.assertEqual(EmailMessageModel.objects.count(), 1)
        self.assertEqual(EmailMessageAttachmentsData.objects.count(), 0)
Пример #4
0
 def test_send_with_email_message(self):
     """
     Tests sending an ``EmailMessage`` with the ``SendGridEmailBackend``.
     """
     email = SendGridEmailMessage(
         "Your new account!",
         "Thanks for signing up.",
         '*****@*****.**',
         ['*****@*****.**'],
         connection=self.connection,
     )
     email.send()
Пример #5
0
    def test_email_sent_signal_has_message(self):
        """
        Tests the existence of the ``message`` keywork arg from the ``sendgrid_email_sent`` signal.
        """
        @receiver(sendgrid_email_sent)
        def receive_sendgrid_email_sent(*args, **kwargs):
            """
            Receives sendgrid_email_sent signals.
            """
            self.assertTrue("response" in kwargs)
            self.assertTrue("message" in kwargs)

        email = SendGridEmailMessage(to=TEST_RECIPIENTS, from_email=TEST_SENDER_EMAIL)
        email.send()
Пример #6
0
def send_registration_email_to_new_user(user, emailOptions=REGISTRATION_EMAIL_SPEC):
    """
    Sends a registration email to ``user``.
    """
    user = get_user(user)

    registrationEmail = SendGridEmailMessage(
        to=[user.email],
        **emailOptions
    )
    registrationEmail.sendgrid_headers.setCategory("Registration")
    registrationEmail.sendgrid_headers.setUniqueArgs({"user_id": user.id})
    response = registrationEmail.send()

    return response
Пример #7
0
    def setUp(self):

        self.attachments = {
            "file1.csv": "name,age\r\nryan,28",
            # "file2.csv": "name,age\r\nryan,28"
        }

        emailMessage = SendGridEmailMessage(
            to=TEST_RECIPIENTS,
            from_email=TEST_SENDER_EMAIL)
        for name, contents in self.attachments.items():
            emailMessage.attach(name, contents)

        response = emailMessage.send()
        self.assertEqual(response, 1)
        self.assertEqual(EmailMessageModel.objects.count(), 1)
        self.assertEqual(EmailMessageAttachmentsData.objects.count(), 1)
Пример #8
0
    def test_send_email_sends_signal(self):
        """
        Tests that sending a ``SendGridEmailMessage`` sends a ``sendgrid_email_sent`` signal.
        """
        @receiver(sendgrid_email_sent)
        def receive_sendgrid_email_sent(*args, **kwargs):
            """
            Receives sendgrid_email_sent signals.
            """
            self.signalsReceived["sendgrid_email_sent"].append(1)
            return True

        email = SendGridEmailMessage(to=TEST_RECIPIENTS, from_email=TEST_SENDER_EMAIL)
        email.send()

        numEmailSentSignalsRecieved = sum(self.signalsReceived["sendgrid_email_sent"])
        self.assertEqual(numEmailSentSignalsRecieved, 1)
Пример #9
0
    def test_unique_args_persist(self):
        """
        Tests that unique args are not lost due to sending adding the ``message_id`` arg.
        """
        email = SendGridEmailMessage(to=TEST_RECIPIENTS, from_email=TEST_SENDER_EMAIL)
        uniqueArgs = {
            "unique_arg_1": 1,
            "unique_arg_2": 2,
            "unique_arg_3": 3,
        }
        email.sendgrid_headers.setUniqueArgs(uniqueArgs)
        email.send()

        for k, v in uniqueArgs.items():
            self.assertEqual(v, email.sendgrid_headers.data["unique_args"][k])

        self.assertTrue(email.sendgrid_headers.data["unique_args"]["message_id"])
Пример #10
0
class UpdateFiltersTests(TestCase):
    """docstring for SendWithFiltersTests"""
    def setUp(self):
        """docstring for setUp"""
        self.email = SendGridEmailMessage(to=TEST_RECIPIENTS, from_email=TEST_SENDER_EMAIL)

    def test_update_filters(self):
        """
        Tests SendGrid filter functionality.
        """
        filterSpec = {
            "subscriptiontrack": {
                "enable": 1,
            },
            "opentrack": {
                "enable": 0,
            },
        }
        update_filters(self.email, filterSpec)
        self.email.send()
Пример #11
0
    def test_send_with_single_category(self):
        @receiver(sendgrid_email_sent)
        def receive_sendgrid_email_sent(*args, **kwargs):
            """
            Receives sendgrid_email_sent signals.
            """
            emailMessage = kwargs["message"]
            sendgridHeadersData = emailMessage.sendgrid_headers.data

            expectedCategory = self.testCategoryNames[0]
            self.assertEqual(sendgridHeadersData["category"], expectedCategory)

        sendgridEmailMessage = SendGridEmailMessage(
            to=TEST_RECIPIENTS, from_email=TEST_SENDER_EMAIL)
        sendgridEmailMessage.sendgrid_headers.setCategory(self.testCategoryNames[0])
        sendgridEmailMessage.update_headers()
        sendgridEmailMessage.send()

        category = self.assert_category_exists(self.testCategoryNames[0])
        self.assertTrue(category)
Пример #12
0
def send_simple_email(request):
    if request.method == 'POST':
        form = EmailForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data["subject"]
            message = form.cleaned_data["message"]
            from_email = form.cleaned_data["sender"]
            recipient_list = form.cleaned_data["to"]
            recipient_list = [r.strip() for r in recipient_list.split(",")]
            categoryData = form.cleaned_data["categories"]
            categories = parse_csv_string(categoryData)
            html = form.cleaned_data["html"]
            enable_gravatar = form.cleaned_data["enable_gravatar"]
            # enable_click_tracking = form.cleaned_data["enable_click_tracking"]
            add_unsubscribe_link = form.cleaned_data["add_unsubscribe_link"]

            if html:
                sendGridEmail = SendGridEmailMultiAlternatives(
                    subject,
                    message,
                    from_email,
                    recipient_list,
                )
                sendGridEmail.attach_alternative(message, "text/html")
            else:
                sendGridEmail = SendGridEmailMessage(
                    subject,
                    message,
                    from_email,
                    recipient_list,
                )

            if categories:
                logger.debug("Categories {c} were given".format(c=categories))
                # The SendGrid Event API will POST different data for
                # single/multiple category messages.
                if len(categories) == 1:
                    sendGridEmail.sendgrid_headers.setCategory(categories[0])
                elif len(categories) > 1:
                    sendGridEmail.sendgrid_headers.setCategory(categories)
                sendGridEmail.update_headers()

            filterSpec = {}
            if enable_gravatar:
                logger.debug("Enable Gravatar was selected")
                filterSpec["gravatar"] = {"enable": 1}

            if enable_gravatar:
                logger.debug("Enable click tracking was selected")
                filterSpec["clicktrack"] = {"enable": 1}

            if add_unsubscribe_link:
                logger.debug("Add unsubscribe link was selected")
                # sendGridEmail.sendgrid_headers.add
                filterSpec["subscriptiontrack"] = {
                    "enable": 1,
                    "text/html": "<p>Unsubscribe <%Here%></p>",
                }

            if filterSpec:
                filterutils.update_filters(sendGridEmail,
                                           filterSpec,
                                           validate=True)

            logger.debug("Sending SendGrid email {e}".format(e=sendGridEmail))
            response = sendGridEmail.send()
            logger.debug("Response {r}".format(r=response))

            if response == 1:
                msg = "Your message was sent"
                msgType = messages.SUCCESS
            else:
                msg = "The was en error sending your message"
                msgType = messages.ERROR
            messages.add_message(request, msgType, msg)

            return HttpResponseRedirect("/")
    else:
        form = EmailForm()

    c = {"form": form}
    c.update(csrf(request))
    return render_to_response('main/send_email.html', c)
Пример #13
0
 def setUp(self):
     self.email = SendGridEmailMessage(to=TEST_RECIPIENTS, from_email=TEST_SENDER_EMAIL)
     self.email.send()
     self.rf = RequestFactory()
Пример #14
0
class SendGridEventTest(TestCase):
    def setUp(self):
        self.email = SendGridEmailMessage(to=TEST_RECIPIENTS, from_email=TEST_SENDER_EMAIL)
        self.email.send()
        self.rf = RequestFactory()

    def test_event_email_exists(self):
        event_count = Event.objects.count()
        post_data = {
            "message_id": self.email.message_id,
            "email": self.email.from_email,
            "event": "OPEN",
            }
        request = self.rf.post('/sendgrid/events', post_data)
        handle_single_event_request(request)
        # Event created
        self.assertEqual(Event.objects.count(), event_count + 1)
        # Email matches original message_id
        self.assertEqual(
            Event.objects.get().email_message.message_id, self.email.message_id.__str__())

    def verify_event_with_missing_email(self, post_data):
        event_count = Event.objects.count()
        email_count = EmailMessageModel.objects.count()

        for key in UNIQUE_ARGS_STORED_FOR_EVENTS_WITHOUT_MESSAGE_ID:
            post_data[key] = key+"_value"

        request = self.rf.post('/sendgrid/events', post_data)
        handle_single_event_request(request)

        if SENDGRID_CREATE_MISSING_EMAIL_MESSAGES:
            delta = 1
        else:
            delta = 0

        # event created
        self.assertEqual(Event.objects.count(), event_count + delta)
        # email created
        self.assertEqual(EmailMessageModel.objects.count(), email_count + delta)

        if SENDGRID_CREATE_MISSING_EMAIL_MESSAGES:
            event = Event.objects.get(email=post_data['email'])
            emailMessage = event.email_message
            # check to_email
            self.assertEqual(event.email_message.to_email, event.email)

            # check unique args
            for key in UNIQUE_ARGS_STORED_FOR_EVENTS_WITHOUT_MESSAGE_ID:
                self.assertEqual(
                    post_data[key], emailMessage.uniqueargument_set.get(argument__key=key).data)

            # post another event
            request = self.rf.post('/sendgrid/events', post_data)
            handle_single_event_request(request)

            # should be same email_count
            self.assertEqual(EmailMessageModel.objects.count(), email_count + 1)

    def test_event_email_doesnt_exist(self):
        postData = {
            "message_id": 'a5df',
            "email": self.email.to[0],
            "event": "OPEN",
            "category": ["test_category", "another_test_category"],
        }

        self.verify_event_with_missing_email(postData)

    def test_event_no_message_id(self):
        postData = {
            "email": self.email.to[0],
            "event": "OPEN",
            "category": "test_category",
        }
        self.verify_event_with_missing_email(postData)

    def test_event_email_doesnt_exist_no_category(self):
        postData = {
            "message_id": 'a5df',
            "email": self.email.to[0],
            "event": "OPEN"
        }

        self.verify_event_with_missing_email(postData)
Пример #15
0
 def setUp(self):
     """docstring for setUp"""
     self.email = SendGridEmailMessage(to=TEST_RECIPIENTS, from_email=TEST_SENDER_EMAIL)
Пример #16
0
 def test_email_has_unique_id(self):
     """
     Tests the existence of the ``SendGridEmailMessage._message_id`` attribute.
     """
     email = SendGridEmailMessage()
     self.assertTrue(email._message_id)