コード例 #1
0
ファイル: api_test.py プロジェクト: mitodl/micromasters
 def test_send_with_sender_address(self, mock_post):
     """
     Test that specifying a sender address in our mail API functions will result in an email
     with the sender address in the 'from' field
     """
     sender_address = '*****@*****.**'
     MailgunClient.send_batch(
         'email subject', 'email body', self.batch_recipient_arg, sender_address=sender_address
     )
     MailgunClient.send_individual_email(
         'email subject', 'email body', self.individual_recipient_arg, sender_address=sender_address
     )
     for args in mock_post.call_args_list:
         _, called_kwargs = args
         assert called_kwargs['data']['from'] == sender_address
コード例 #2
0
 def test_send_individual_email(self, sender_name, mock_post):
     """
     Test that MailgunClient.send_individual_email() sends an individual message
     """
     context = {"abc": {"def": "xyz"}}
     response = MailgunClient.send_individual_email(
         subject="email subject",
         html_body="html",
         text_body="text",
         recipient="*****@*****.**",
         recipient_variables=context,
         sender_name=sender_name,
     )
     assert response.status_code == HTTP_200_OK
     assert mock_post.called
     called_args, called_kwargs = mock_post.call_args
     assert list(called_args)[0] == "{}/{}".format(settings.MAILGUN_URL, "messages")
     assert called_kwargs["auth"] == ("api", settings.MAILGUN_KEY)
     assert called_kwargs["data"]["html"].startswith("html")
     assert called_kwargs["data"]["text"].startswith("text")
     assert called_kwargs["data"]["subject"] == "email subject"
     assert called_kwargs["data"]["to"] == ["*****@*****.**"]
     assert called_kwargs["data"]["recipient-variables"] == json.dumps(
         {"*****@*****.**": context}
     )
     if sender_name is not None:
         self.assertEqual(
             called_kwargs["data"]["from"],
             "{sender_name} <{email}>".format(
                 sender_name=sender_name, email=settings.EMAIL_SUPPORT
             ),
         )
     else:
         self.assertEqual(called_kwargs["data"]["from"], settings.EMAIL_SUPPORT)
コード例 #3
0
ファイル: views.py プロジェクト: mitodl/micromasters
 def post(self, request, *args, **kargs):  # pylint: disable=unused-argument
     """
     POST method handler
     """
     sender_user = request.user
     school = self.get_object()
     enrollment = get_object_or_404(ProgramEnrollment, hash=request.data['enrollment_hash'])
     mailgun_response = MailgunClient.send_individual_email(
         subject="MicroMasters Program Record",
         body=render_to_string(
             'grades_record_email.html',
             {
                 'user_full_name': sender_user.profile.full_name,
                 'pathway_name': school.name,
                 'program_name': enrollment.program.title,
                 'record_link': request.build_absolute_uri(
                     reverse('grade_records', args=[request.data['enrollment_hash']])
                 ),
             }),
         recipient=school.email,
         sender_address=sender_user.email,
         sender_name=sender_user.profile.display_name,
     )
     return Response(
         status=mailgun_response.status_code,
         data=generate_mailgun_response_json(mailgun_response)
     )
コード例 #4
0
 def test_send_individual_email(self, sender_name, mock_post):
     """
     Test that MailgunClient.send_individual_email() sends an individual message
     """
     context = {'abc': {'def': 'xyz'}}
     response = MailgunClient.send_individual_email(
         subject='email subject',
         body='email body',
         recipient='*****@*****.**',
         recipient_variables=context,
         sender_name=sender_name,
     )
     assert response.status_code == HTTP_200_OK
     assert mock_post.called
     called_args, called_kwargs = mock_post.call_args
     assert list(called_args)[0] == '{}/{}'.format(settings.MAILGUN_URL,
                                                   'messages')
     assert called_kwargs['auth'] == ('api', settings.MAILGUN_KEY)
     assert called_kwargs['data']['text'].startswith('email body')
     assert called_kwargs['data']['subject'] == 'email subject'
     assert called_kwargs['data']['to'] == ['*****@*****.**']
     assert called_kwargs['data']['recipient-variables'] == json.dumps(
         {'*****@*****.**': context})
     if sender_name is not None:
         self.assertEqual(
             called_kwargs['data']['from'],
             "{sender_name} <{email}>".format(sender_name=sender_name,
                                              email=settings.EMAIL_SUPPORT))
     else:
         self.assertEqual(called_kwargs['data']['from'],
                          settings.EMAIL_SUPPORT)
コード例 #5
0
ファイル: api_test.py プロジェクト: mitodl/micromasters
 def test_send_individual_email(self, sender_name, mock_post):
     """
     Test that MailgunClient.send_individual_email() sends an individual message
     """
     context = {'abc': {'def': 'xyz'}}
     response = MailgunClient.send_individual_email(
         subject='email subject',
         body='email body',
         recipient='*****@*****.**',
         recipient_variables=context,
         sender_name=sender_name,
     )
     assert response.status_code == HTTP_200_OK
     assert mock_post.called
     called_args, called_kwargs = mock_post.call_args
     assert list(called_args)[0] == '{}/{}'.format(settings.MAILGUN_URL, 'messages')
     assert called_kwargs['auth'] == ('api', settings.MAILGUN_KEY)
     assert called_kwargs['data']['text'].startswith('email body')
     assert called_kwargs['data']['subject'] == 'email subject'
     assert called_kwargs['data']['to'] == ['*****@*****.**']
     assert called_kwargs['data']['recipient-variables'] == json.dumps({'*****@*****.**': context})
     if sender_name is not None:
         self.assertEqual(
             called_kwargs['data']['from'],
             "{sender_name} <{email}>".format(sender_name=sender_name, email=settings.EMAIL_SUPPORT)
         )
     else:
         self.assertEqual(called_kwargs['data']['from'], settings.EMAIL_SUPPORT)
コード例 #6
0
 def post(self, request, *args, **kargs):  # pylint: disable=unused-argument
     """
     POST method handler
     """
     sender_user = request.user
     school = self.get_object()
     enrollment = get_object_or_404(ProgramEnrollment,
                                    hash=request.data['enrollment_hash'])
     mailgun_response = MailgunClient.send_individual_email(
         subject="MicroMasters Program Record",
         body=render_to_string(
             'grades_record_email.html', {
                 'user_full_name':
                 sender_user.profile.full_name,
                 'pathway_name':
                 school.name,
                 'program_name':
                 enrollment.program.title,
                 'record_link':
                 request.build_absolute_uri(
                     reverse('grade_records',
                             args=[request.data['enrollment_hash']])),
             }),
         recipient=school.email,
         sender_address=sender_user.email,
         sender_name=sender_user.profile.display_name,
     )
     return Response(status=mailgun_response.status_code,
                     data=generate_mailgun_response_json(mailgun_response))
コード例 #7
0
 def test_send_with_sender_address(self, mock_post):
     """
     Test that specifying a sender address in our mail API functions will result in an email
     with the sender address in the 'from' field
     """
     sender_address = '*****@*****.**'
     MailgunClient.send_batch('email subject',
                              'email body',
                              self.batch_recipient_arg,
                              sender_address=sender_address)
     MailgunClient.send_individual_email('email subject',
                                         'email body',
                                         self.individual_recipient_arg,
                                         sender_address=sender_address)
     for args in mock_post.call_args_list:
         _, called_kwargs = args
         assert called_kwargs['data']['from'] == sender_address
コード例 #8
0
 def test_send_with_sender_address(self, mock_post):
     """
     Test that specifying a sender address in our mail API functions will result in an email
     with the sender address in the 'from' field
     """
     sender_address = "*****@*****.**"
     MailgunClient.send_batch(
         "email subject",
         "html",
         "text",
         self.batch_recipient_arg,
         sender_address=sender_address,
     )
     MailgunClient.send_individual_email(
         "email subject",
         "html",
         "text",
         self.individual_recipient_arg,
         sender_address=sender_address,
     )
     for args in mock_post.call_args_list:
         _, called_kwargs = args
         assert called_kwargs["data"]["from"] == sender_address
コード例 #9
0
 def post(self, request, *args, **kargs):  # pylint: disable=unused-argument
     """
     POST method handler
     """
     sender_user = request.user
     recipient_user = self.get_object().user
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     mailgun_response = MailgunClient.send_individual_email(
         subject=request.data['email_subject'],
         body=request.data['email_body'],
         recipient=recipient_user.email,
         sender_address=sender_user.email,
         sender_name=sender_user.profile.display_name,
     )
     return Response(status=mailgun_response.status_code,
                     data=generate_mailgun_response_json(mailgun_response))
コード例 #10
0
    def test_send_individual_email_error(self, raise_for_status, mock_post):
        """
        Test handling of errors for send_individual_email
        """
        mock_post.return_value = Mock(spec=Response,
                                      status_code=HTTP_400_BAD_REQUEST,
                                      json=mocked_json())

        response = MailgunClient.send_individual_email(
            subject='email subject',
            body='email body',
            recipient='*****@*****.**',
            raise_for_status=raise_for_status,
        )

        assert response.raise_for_status.called is raise_for_status
        assert response.status_code == HTTP_400_BAD_REQUEST
        assert response.json() == {}
コード例 #11
0
ファイル: views.py プロジェクト: mitodl/micromasters
 def post(self, request, *args, **kargs):  # pylint: disable=unused-argument
     """
     POST method handler
     """
     sender_user = request.user
     recipient_user = self.get_object().user
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     mailgun_response = MailgunClient.send_individual_email(
         subject=request.data['email_subject'],
         body=request.data['email_body'],
         recipient=recipient_user.email,
         sender_address=sender_user.email,
         sender_name=sender_user.profile.display_name,
     )
     return Response(
         status=mailgun_response.status_code,
         data=generate_mailgun_response_json(mailgun_response)
     )
コード例 #12
0
ファイル: api_test.py プロジェクト: mitodl/micromasters
    def test_send_individual_email_error(self, raise_for_status, mock_post):
        """
        Test handling of errors for send_individual_email
        """
        mock_post.return_value = Mock(
            spec=Response,
            status_code=HTTP_400_BAD_REQUEST,
            json=mocked_json()
        )

        response = MailgunClient.send_individual_email(
            subject='email subject',
            body='email body',
            recipient='*****@*****.**',
            raise_for_status=raise_for_status,
        )

        assert response.raise_for_status.called is raise_for_status
        assert response.status_code == HTTP_400_BAD_REQUEST
        assert response.json() == {}
コード例 #13
0
    def post(self, request, *args, **kargs):  # pylint: disable=unused-argument
        """
        POST method handler
        """
        sender_user = request.user
        school = self.get_object()
        enrollment = get_object_or_404(
            ProgramEnrollment, share_hash=request.data['enrollment_hash'])
        mailgun_response = MailgunClient.send_individual_email(
            subject="MicroMasters Program Record",
            body=render_to_string(
                'grades_record_email.html', {
                    'user_full_name':
                    sender_user.profile.full_name,
                    'pathway_name':
                    school.name,
                    'program_name':
                    enrollment.program.title,
                    'record_link':
                    request.build_absolute_uri(
                        reverse("shared_grade_records",
                                kwargs=dict(
                                    enrollment_id=enrollment.id,
                                    record_share_hash=enrollment.share_hash))),
                }),
            recipient=school.email,
            sender_address=sender_user.email,
            sender_name=sender_user.profile.display_name,
        )
        if mailgun_response.status_code == 200:
            _ = MicromastersLearnerRecordShare.objects.get_or_create(
                user=sender_user,
                program=enrollment.program,
                partner_school=school)

        return Response(status=mailgun_response.status_code,
                        data=generate_mailgun_response_json(mailgun_response))