another stab at email sending

This commit is contained in:
matthewswspence 2024-09-18 14:33:44 -05:00
parent 9bbcb98071
commit b8d697ebf0
No known key found for this signature in database
GPG key ID: FB458202A7852BA4
4 changed files with 74 additions and 5 deletions

View file

@ -20,7 +20,7 @@ applications:
# Tell Django where it is being hosted
DJANGO_BASE_URL: https://getgov-ms.app.cloud.gov
# Tell Django how much stuff to log
DJANGO_LOG_LEVEL: INFO
DJANGO_LOG_LEVEL: DEBUG
# default public site location
GETGOV_PUBLIC_SITE_URL: https://get.gov
# Flag to disable/enable features in prod environments

View file

@ -61,6 +61,22 @@ class TestEmails(TestCase):
# Assert that an email wasn't sent
self.assertFalse(self.mock_client.send_email.called)
@boto3_mocking.patching
def test_email_with_cc(self):
"""Test sending email with cc works"""
with boto3_mocking.clients.handler_for("sesv2", self.mock_client_class):
send_templated_email(
"test content",
"test subject",
"doesnotexist@igorville.com",
context={"domain_request": self},
bcc_address=None,
cc=["test_email1@example.com", "test_email2@example.com"]
)
# check that an email was sent
self.assertTrue(self.mock_client.send_email.called)
@boto3_mocking.patching
@less_console_noise_decorator
def test_submission_confirmation(self):

View file

@ -2,6 +2,7 @@ from unittest import skip
from unittest.mock import MagicMock, ANY, patch
from django.conf import settings
from django.test import override_settings
from django.urls import reverse
from django.contrib.auth import get_user_model
from waffle.testutils import override_flag
@ -10,6 +11,7 @@ from registrar.models.utility.portfolio_helper import UserPortfolioRoleChoices
from .common import MockEppLib, MockSESClient, create_user # type: ignore
from django_webtest import WebTest # type: ignore
import boto3_mocking # type: ignore
from django.middleware.csrf import get_token
from registrar.utility.errors import (
NameserverError,
@ -1973,3 +1975,49 @@ class TestDomainDNSSEC(TestDomainOverview):
self.assertContains(
result, str(DsDataError(code=DsDataErrorCodes.INVALID_DIGEST_SHA256)), count=2, status_code=200
)
# class TestDomainChangeNotifications(TestDomainOverview):
# """Test email notifications on updates to domain information"""
# @classmethod
# def setUpClass(cls):
# super().setUpClass()
# allowed_emails = [
# AllowedEmail(email="info@example.com"),
# ]
# AllowedEmail.objects.bulk_create(allowed_emails)
# @classmethod
# def tearDownClass(cls):
# super().tearDownClass()
# AllowedEmail.objects.all().delete()
# def test_notification_email_sent_on_org_name_change(self):
# """Test that an email is sent when the organization name is changed."""
# with patch('registrar.utility.email.boto3.client') as mock_boto3_client:
# mock_ses_client = mock_boto3_client.return_value
# self.domain_information.organization_name = "Town of Igorville"
# self.domain_information.save()
# org_name_page = self.app.get(reverse("domain-org-name-address", kwargs={"pk": self.domain.id}))
# session_id = self.app.cookies[settings.SESSION_COOKIE_NAME]
# org_name_page.form["organization_name"] = "Not igorville"
# self.app.set_cookie(settings.SESSION_COOKIE_NAME, session_id)
# success_result_page = org_name_page.form.submit()
# # Check that the page loads successfully
# self.assertEqual(success_result_page.status_code, 200)
# self.assertContains(success_result_page, "Not igorville")
# # Check that an email was sent
# mock_ses_client.send_email.assert_called_once()
# # Check email content
# call_kwargs = mock_ses_client.send_email.call_args[1]
# self.assertEqual(call_kwargs['FromEmailAddress'], settings.DEFAULT_FROM_EMAIL)
# self.assertIn('Domain information updated', call_kwargs['Content']['Simple']['Subject']['Data'])
# self.assertIn('City of Igorville', call_kwargs['Content']['Simple']['Body']['Text']['Data'])

View file

@ -51,7 +51,10 @@ def send_templated_email(
# Raises an error if we cannot send an email (due to restrictions).
# Does nothing otherwise.
_can_send_email(to_address, bcc_address)
sendable_cc_addresses = get_sendable_addresses(cc_addresses)
sendable_cc_addresses, blocked_cc_addresses = get_sendable_addresses(cc_addresses)
if len(sendable_cc_addresses) < len(cc_addresses):
logger.warning("Some CC'ed addresses were removed: %s.", blocked_cc_addresses)
template = get_template(template_name)
@ -107,6 +110,7 @@ def send_templated_email(
},
},
)
logger.info("Email sent to %s, bcc %s, cc %s", to_address, bcc_address, cc_addresses)
else:
ses_client = boto3.client(
"ses",
@ -138,10 +142,10 @@ def _can_send_email(to_address, bcc_address):
if bcc_address and not AllowedEmail.is_allowed_email(bcc_address):
raise EmailSendingError(message.format(bcc_address))
def get_sendable_addresses(addresses: list[str]) -> list[str]:
def get_sendable_addresses(addresses: list[str]) -> tuple[list[str], list[str]]:
"""Checks whether a list of addresses can be sent to.
Returns: a lists of all provided addresses that are ok to send to
Returns: a lists of all provided addresses that are ok to send to and a list of addresses that were blocked.
Paramaters:
@ -157,8 +161,9 @@ def get_sendable_addresses(addresses: list[str]) -> list[str]:
else:
AllowedEmail = apps.get_model("registrar", "AllowedEmail")
allowed_emails = [address for address in addresses if (address and AllowedEmail.is_allowed_email(address))]
blocked_emails = [address for address in addresses if (address and not AllowedEmail.is_allowed_email(address))]
return allowed_emails
return allowed_emails, blocked_emails
def wrap_text_and_preserve_paragraphs(text, width):