def create_content_for_notification(template, personalisation): if template.template_type == EMAIL_TYPE: template_object = PlainTextEmailTemplate( { 'content': template.content, 'subject': template.subject, 'template_type': template.template_type, }, personalisation, ) if template.template_type == SMS_TYPE: template_object = SMSMessageTemplate( { 'content': template.content, 'template_type': template.template_type, }, personalisation, ) if template.template_type == LETTER_TYPE: template_object = LetterPrintTemplate( { 'content': template.content, 'subject': template.subject, 'template_type': template.template_type, }, personalisation, contact_block=template.reply_to_text, ) check_placeholders(template_object) return template_object
def send_email_to_provider(notification): service = notification.service if not service.active: technical_failure(notification=notification) return if notification.status == 'created': provider = provider_to_use(EMAIL_TYPE, notification.id) current_app.logger.debug( "Starting sending EMAIL {} to provider at {}".format(notification.id, datetime.utcnow()) ) template_dict = dao_get_template_by_id(notification.template_id, notification.template_version).__dict__ html_email = HTMLEmailTemplate( template_dict, values=notification.personalisation, **get_html_email_options(service) ) plain_text_email = PlainTextEmailTemplate( template_dict, values=notification.personalisation ) if service.research_mode or notification.key_type == KEY_TYPE_TEST: reference = str(create_uuid()) notification.billable_units = 0 notification.reference = reference update_notification(notification, provider) send_email_response(reference, notification.to) else: from_address = '"{}" <{}@{}>'.format(service.name, service.email_from, current_app.config['NOTIFY_EMAIL_DOMAIN']) email_reply_to = notification.reply_to_text reference, status = provider.send_email( from_address, validate_and_format_email_address(notification.to), plain_text_email.subject, body=str(plain_text_email), html_body=str(html_email), reply_to_address=validate_and_format_email_address(email_reply_to) if email_reply_to else None, ) notification.reference = reference update_notification(notification, provider, status=status) current_app.logger.debug("SENT_MAIL: {} -- {}".format( validate_and_format_email_address(notification.to), str(plain_text_email)) ) current_app.logger.debug( "Email {} sent to provider at {}".format(notification.id, notification.sent_at) ) delta_milliseconds = (datetime.utcnow() - notification.created_at).total_seconds() * 1000 statsd_client.timing("email.total-time", delta_milliseconds)
def send_email_to_provider(notification): service = notification.service if not service.active: technical_failure(notification=notification) return if notification.status == 'created': provider = provider_to_use(EMAIL_TYPE) template_dict = dao_get_template_by_id( notification.template_id, notification.template_version).__dict__ html_email = HTMLEmailTemplate(template_dict, values=notification.personalisation, **get_html_email_options(service)) plain_text_email = PlainTextEmailTemplate( template_dict, values=notification.personalisation) if service.research_mode or notification.key_type == KEY_TYPE_TEST: notification.reference = str(create_uuid()) update_notification_to_sending(notification, provider) send_email_response(notification.reference, notification.to) else: from_address = '"{}" <{}@{}>'.format( service.name, service.email_from, current_app.config['NOTIFY_EMAIL_DOMAIN']) email_reply_to = notification.reply_to_text reference = provider.send_email( from_address, validate_and_format_email_address(notification.to), plain_text_email.subject, body=str(plain_text_email), html_body=str(html_email), reply_to_address=validate_and_format_email_address( email_reply_to) if email_reply_to else None, ) notification.reference = reference update_notification_to_sending(notification, provider) delta_seconds = (datetime.utcnow() - notification.created_at).total_seconds() if notification.key_type == KEY_TYPE_TEST: statsd_client.timing("email.test-key.total-time", delta_seconds) else: statsd_client.timing("email.live-key.total-time", delta_seconds) if str(service.id) in current_app.config.get( 'HIGH_VOLUME_SERVICE'): statsd_client.timing("email.live-key.high-volume.total-time", delta_seconds) else: statsd_client.timing( "email.live-key.not-high-volume.total-time", delta_seconds)
def test_escaping_govuk_in_email_templates(): template_content = "GOV.UK" expected = "GOV.\u200BUK" assert unlink_govuk_escaped(template_content) == expected template_json = { 'content': template_content, 'subject': '', 'template_type': 'email' } assert expected in str(PlainTextEmailTemplate(template_json)) assert expected in str(HTMLEmailTemplate(template_json))
def test_escaping_govuk_in_email_templates(template_content, expected): assert unlink_govuk_escaped(template_content) == expected assert expected in str( PlainTextEmailTemplate({ 'content': template_content, 'subject': '' })) assert expected in str( HTMLEmailTemplate({ 'content': template_content, 'subject': '' }))
def test_plain_text_email_whitespace(): email = PlainTextEmailTemplate({'subject': 'foo', 'content': ( '# Heading\n' '\n' '1. one\n' '2. two\n' '3. three\n' '\n' '***\n' '\n' '# Heading\n' '\n' 'Paragraph\n' '\n' 'Paragraph\n' '\n' '^ callout\n' '\n' '1. one not four\n' '1. two not five' )}) assert str(email) == ( 'Heading\n' '-----------------------------------------------------------------\n' '\n' '1. one\n' '2. two\n' '3. three\n' '\n' '=================================================================\n' '\n' '\n' 'Heading\n' '-----------------------------------------------------------------\n' '\n' 'Paragraph\n' '\n' 'Paragraph\n' '\n' 'callout\n' '\n' '1. one not four\n' '2. two not five\n' )
def send_email_to_provider(notification): service = notification.service if not service.active: technical_failure(notification=notification) return # TODO: no else - replace with if statement raising error / logging when not 'created' if notification.status == 'created': provider = provider_to_use(notification) # TODO: remove that code or extract attachment handling to separate method # Extract any file objects from the personalization file_keys = [ k for k, v in (notification.personalisation or {}).items() if isinstance(v, dict) and 'document' in v ] attachments = [] personalisation_data = notification.personalisation.copy() for key in file_keys: # Check if a MLWR sid exists if (current_app.config["MLWR_HOST"] and 'mlwr_sid' in personalisation_data[key]['document'] and personalisation_data[key]['document']['mlwr_sid'] != "false"): mlwr_result = check_mlwr( personalisation_data[key]['document']['mlwr_sid']) if "state" in mlwr_result and mlwr_result[ "state"] == "completed": # Update notification that it contains malware if "submission" in mlwr_result and mlwr_result[ "submission"]['max_score'] >= 500: malware_failure(notification=notification) return else: # Throw error so celery will retry in sixty seconds raise MalwarePendingException try: response = requests.get( personalisation_data[key]['document']['direct_file_url']) if response.headers['Content-Type'] == 'application/pdf': attachments.append({ "name": "{}.pdf".format(key), "data": response.content }) except Exception: current_app.logger.error( "Could not download and attach {}".format( personalisation_data[key]['document'] ['direct_file_url'])) personalisation_data[key] = personalisation_data[key]['document'][ 'url'] template_dict = dao_get_template_by_id( notification.template_id, notification.template_version).__dict__ html_email = HTMLEmailTemplate(template_dict, values=personalisation_data, **get_html_email_options( notification, provider)) plain_text_email = PlainTextEmailTemplate(template_dict, values=personalisation_data) if current_app.config["SCAN_FOR_PII"]: contains_pii(notification, str(plain_text_email)) if service.research_mode or notification.key_type == KEY_TYPE_TEST: notification.reference = str(create_uuid()) update_notification_to_sending(notification, provider) send_email_response(notification.reference, notification.to) else: email_reply_to = notification.reply_to_text reference = provider.send_email( source=compute_source_email_address(service, provider), to_addresses=validate_and_format_email_address( notification.to), subject=plain_text_email.subject, body=str(plain_text_email), html_body=str(html_email), reply_to_address=validate_and_format_email_address( email_reply_to) if email_reply_to else None, attachments=attachments) notification.reference = reference update_notification_to_sending(notification, provider) current_app.logger.info( f"Saved provider reference: {reference} for notification id: {notification.id}" ) delta_milliseconds = (datetime.utcnow() - notification.created_at).total_seconds() * 1000 statsd_client.timing("email.total-time", delta_milliseconds)
def send_email_to_provider(notification): service = notification.service if not service.active: technical_failure(notification=notification) return if notification.status == 'created': provider = provider_to_use(EMAIL_TYPE, notification.id) # Extract any file objects from the personalization file_keys = [ k for k, v in (notification.personalisation or {}).items() if isinstance(v, dict) and 'document' in v ] attachments = [] personalisation_data = notification.personalisation.copy() for key in file_keys: # Check if a MLWR sid exists if (current_app.config["MLWR_HOST"] and 'mlwr_sid' in personalisation_data[key]['document'] and personalisation_data[key]['document']['mlwr_sid'] != "false"): mlwr_result = check_mlwr(personalisation_data[key]['document']['mlwr_sid']) if "state" in mlwr_result and mlwr_result["state"] == "completed": # Update notification that it contains malware if "submission" in mlwr_result and mlwr_result["submission"]['max_score'] >= 500: malware_failure(notification=notification) return else: # Throw error so celery will retry in sixty seconds raise MalwarePendingException try: req = urllib.request.Request(personalisation_data[key]['document']['direct_file_url']) with urllib.request.urlopen(req) as response: buffer = response.read() mime_type = magic.from_buffer(buffer, mime=True) if mime_type == 'application/pdf': attachments.append({"name": "{}.pdf".format(key), "data": buffer}) except Exception: current_app.logger.error( "Could not download and attach {}".format(personalisation_data[key]['document']['direct_file_url']) ) personalisation_data[key] = personalisation_data[key]['document']['url'] template_dict = dao_get_template_by_id(notification.template_id, notification.template_version).__dict__ html_email = HTMLEmailTemplate( template_dict, values=personalisation_data, **get_html_email_options(service) ) plain_text_email = PlainTextEmailTemplate( template_dict, values=personalisation_data ) if current_app.config["SCAN_FOR_PII"]: contains_pii(notification, str(plain_text_email)) if service.research_mode or notification.key_type == KEY_TYPE_TEST: notification.reference = str(create_uuid()) update_notification_to_sending(notification, provider) send_email_response(notification.reference, notification.to) else: if service.sending_domain is None or service.sending_domain.strip() == "": sending_domain = current_app.config['NOTIFY_EMAIL_DOMAIN'] else: sending_domain = service.sending_domain from_address = '"{}" <{}@{}>'.format(service.name, service.email_from, sending_domain) email_reply_to = notification.reply_to_text reference = provider.send_email( from_address, validate_and_format_email_address(notification.to), plain_text_email.subject, body=str(plain_text_email), html_body=str(html_email), reply_to_address=validate_and_format_email_address(email_reply_to) if email_reply_to else None, attachments=attachments ) notification.reference = reference update_notification_to_sending(notification, provider) delta_milliseconds = (datetime.utcnow() - notification.created_at).total_seconds() * 1000 statsd_client.timing("email.total-time", delta_milliseconds)
def send_email_to_provider(notification): service = notification.service if not service.active: technical_failure(notification=notification) return if notification.status == "created": provider = provider_to_use(EMAIL_TYPE, notification.id) # Extract any file objects from the personalization file_keys = [ k for k, v in (notification.personalisation or {}).items() if isinstance(v, dict) and "document" in v ] attachments = [] personalisation_data = notification.personalisation.copy() for key in file_keys: sending_method = personalisation_data[key]["document"].get( "sending_method") # Check if a MLWR sid exists if (current_app.config["MLWR_HOST"] and "mlwr_sid" in personalisation_data[key]["document"] and personalisation_data[key]["document"]["mlwr_sid"] != "false"): mlwr_result = check_mlwr( personalisation_data[key]["document"]["mlwr_sid"]) if "state" in mlwr_result and mlwr_result[ "state"] == "completed": # Update notification that it contains malware if "submission" in mlwr_result and mlwr_result[ "submission"]["max_score"] >= 500: malware_failure(notification=notification) return else: # Throw error so celery will retry in sixty seconds raise MalwarePendingException if sending_method == "attach": try: req = urllib.request.Request( personalisation_data[key]["document"] ["direct_file_url"]) with urllib.request.urlopen(req) as response: buffer = response.read() filename = personalisation_data[key]["document"].get( "filename") mime_type = personalisation_data[key]["document"].get( "mime_type") attachments.append({ "name": filename, "data": buffer, "mime_type": mime_type, }) except Exception: current_app.logger.error( "Could not download and attach {}".format( personalisation_data[key]["document"] ["direct_file_url"])) del personalisation_data[key] else: personalisation_data[key] = personalisation_data[key][ "document"]["url"] template_dict = dao_get_template_by_id( notification.template_id, notification.template_version).__dict__ # Local Jinja support - Add USE_LOCAL_JINJA_TEMPLATES=True to .env # Add a folder to the project root called 'jinja_templates' # with a copy of 'email_template.jinja2' from notification-utils repo debug_template_path = ( os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if os.environ.get("USE_LOCAL_JINJA_TEMPLATES") == "True" else None) html_email = HTMLEmailTemplate( template_dict, values=personalisation_data, jinja_path=debug_template_path, **get_html_email_options(service), ) plain_text_email = PlainTextEmailTemplate(template_dict, values=personalisation_data) if current_app.config["SCAN_FOR_PII"]: contains_pii(notification, str(plain_text_email)) if service.research_mode or notification.key_type == KEY_TYPE_TEST: notification.reference = send_email_response(notification.to) update_notification_to_sending(notification, provider) else: if service.sending_domain is None or service.sending_domain.strip( ) == "": sending_domain = current_app.config["NOTIFY_EMAIL_DOMAIN"] else: sending_domain = service.sending_domain from_address = '"{}" <{}@{}>'.format(service.name, service.email_from, sending_domain) email_reply_to = notification.reply_to_text reference = provider.send_email( from_address, validate_and_format_email_address(notification.to), plain_text_email.subject, body=str(plain_text_email), html_body=str(html_email), reply_to_address=validate_and_format_email_address( email_reply_to) if email_reply_to else None, attachments=attachments, ) notification.reference = reference update_notification_to_sending(notification, provider) # Record StatsD stats to compute SLOs statsd_client.timing_with_dates("email.total-time", notification.sent_at, notification.created_at) attachments_category = "with-attachments" if attachments else "no-attachments" statsd_key = f"email.{attachments_category}.process_type-{template_dict['process_type']}" statsd_client.timing_with_dates(statsd_key, notification.sent_at, notification.created_at) statsd_client.incr(statsd_key)
@pytest.mark.parametrize('template_instance, expected_placeholders', [ ( SMSMessageTemplate( {"content": "((content))", "subject": "((subject))"}, ), ['content'], ), ( SMSPreviewTemplate( {"content": "((content))", "subject": "((subject))"}, ), ['content'], ), ( PlainTextEmailTemplate( {"content": "((content))", "subject": "((subject))"}, ), ['content', 'subject'], ), ( HTMLEmailTemplate( {"content": "((content))", "subject": "((subject))"}, ), ['content', 'subject'], ), ( EmailPreviewTemplate( {"content": "((content))", "subject": "((subject))"}, ), ['content', 'subject'], ),