Add text wrapping

This commit is contained in:
zandercymatics 2024-06-10 14:24:25 -06:00
parent 67e109748d
commit 4d8d722375
No known key found for this signature in database
GPG key ID: FF4636ABEC9682B7
2 changed files with 30 additions and 1 deletions

View file

@ -628,7 +628,7 @@ class DomainRequest(TimeStampedModel):
logger.error(f"Can't query an approved domain while attempting {called_from}")
def _send_status_update_email(
self, new_status, email_template, email_template_subject, send_email=True, bcc_address=""
self, new_status, email_template, email_template_subject, send_email=True, bcc_address="", wrap_email=False
):
"""Send a status update email to the submitter.
@ -655,6 +655,7 @@ class DomainRequest(TimeStampedModel):
self.submitter.email,
context={"domain_request": self},
bcc_address=bcc_address,
wrap_email=wrap_email,
)
logger.info(f"The {new_status} email sent to: {self.submitter.email}")
except EmailSendingError:
@ -811,6 +812,7 @@ class DomainRequest(TimeStampedModel):
email_template=f"emails/action_needed_reasons/{email_template_name}",
email_template_subject=f"emails/action_needed_reasons/{email_template_subject_name}",
send_email=send_email,
wrap_email=True,
)
@transition(

View file

@ -2,6 +2,7 @@
import boto3
import logging
import textwrap
from datetime import datetime
from django.conf import settings
from django.template.loader import get_template
@ -27,6 +28,7 @@ def send_templated_email(
bcc_address="",
context={},
attachment_file: str = None,
wrap_email = False,
):
"""Send an email built from a template to one email address.
@ -66,6 +68,11 @@ def send_templated_email(
try:
if attachment_file is None:
# Wrap the email body to a maximum width of 80 characters per line.
# Not all email clients support CSS to do this, and our .txt files require parsing.
if wrap_email:
email_body = wrap_text_and_preserve_paragraphs(email_body, width=80)
ses_client.send_email(
FromEmailAddress=settings.DEFAULT_FROM_EMAIL,
Destination=destination,
@ -91,6 +98,26 @@ def send_templated_email(
raise EmailSendingError("Could not send SES email.") from exc
def wrap_text_and_preserve_paragraphs(text, width):
"""
Wraps text to `width` preserving newlines; splits on '\n', wraps segments, rejoins with '\n'.
Args:
text (str): Text to wrap.
width (int): Max width per line, default 80.
Returns:
str: Wrapped text with preserved paragraph structure.
"""
# Split text into paragraphs by newlines
paragraphs = text.split('\n')
# Add \n to any line that exceeds our max length
wrapped_paragraphs = [textwrap.fill(paragraph, width=width) for paragraph in paragraphs]
# Join paragraphs with double newlines
return '\n'.join(wrapped_paragraphs)
def send_email_with_attachment(sender, recipient, subject, body, attachment_file, ses_client):
# Create a multipart/mixed parent container
msg = MIMEMultipart("mixed")