def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): """ Uses govuk notify to deliver email providing a link for the user to reset their password. """ if not settings.NOTIFY_APIKEY: return notifications_client = NotificationsAPIClient(settings.NOTIFY_APIKEY) # TODO: We should look up the template IDs from configuration # somewhere. template_id = '22afa457-ee83-4af2-aab7-db5299f54b6b' del context['user'] del context['email'] context['uid'] = context['uid'].decode("utf-8") try: notifications_client.send_email_notification( email_address=to_email, template_id=template_id, personalisation=context, reference=None) except Exception as e: logger.exception(e) raise e
def send_mail( self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None, ): user = context.get("user") url = context.get("base_url") + reverse( "password_reset_confirm", kwargs={ "uidb64": urlsafe_base64_encode(force_bytes(user.pk)), "token": context.get("token"), }, ) notifications_client = NotificationsAPIClient( settings.NOTIFY_API_KEY, base_url=settings.NOTIFY_ENDPOINT) try: notifications_client.send_email_notification( email_address=user.email, template_id=settings.PASSWORD_RESET_EMAIL_TEMPLATE_ID.get( context.get("language") or "en"), personalisation={ "name": user.name, "url": url, }, ) except HTTPError as e: raise Exception(e)
def __init__(self, config) -> None: super().__init__(config) self.template_id: str = '' self.template_vars: Optional[Dict] = None self.client = NotificationsAPIClient( api_key=self.get_api_key() or self.get_config_value( env_var='GOV_NOTIFY_KEY', section='GovNotify', key='api_key'))
def send_signup_email(to: str, registration_key: str): if config.auth.internal.signup.notify.base_url is not None: nc = NotificationsAPIClient( config.auth.internal.signup.notify.api_key, base_url=config.auth.internal.signup.notify.base_url) nc.send_email_notification( to, config.auth.internal.signup.notify.registration_template, personalisation={ "fqdn": config.ui.fqdn, "registration_key": registration_key }) else: message = dedent(f""" We have received your request to register for {config.ui.fqdn}. To confirm your account registration, please visit the link below: https://{config.ui.fqdn}/login.html?registration_key={registration_key} If you did not make this request, you can safely ignore this email. """) title = f"Confirm your account registration for {config.ui.fqdn}" send_email(title, message, to)
def send_approvals_email(request_id): print('Sending mail') approver, requestor, user, reason, team_name, items_to_approve, sc = get_approval_details( request_id) print(approver) approval_url = 'https://' + settings.DOMAIN_NAME + '/access-requests/' attention_for = get_username(approver) requestor = get_username(requestor) user = get_username(user) emailaddr = get_test_email_addreess(approver) notifications_client = NotificationsAPIClient(settings.GOV_NOTIFY_API_KEY) notifications_client.send_email_notification( email_address=emailaddr, template_id=settings.EMAIL_UUID, personalisation={ 'name': attention_for, 'sc': sc, 'requester': requestor, 'user': user, 'reason': reason, 'team': team_name, 'services': items_to_approve, 'url': approval_url } )
def __send_email__(self, emails, data): notifications_client = NotificationsAPIClient(settings.NOTIFY_API_KEY) FILE_NAME = 'report.csv' with open(FILE_NAME, 'w') as csvFile: f = csv.writer(csvFile) f.writerows(data['csv']) csvFile.close() for to in emails: with open(FILE_NAME, 'rb') as f: response = notifications_client.send_email_notification( email_address=to, template_id=settings.NOTIFY_TEMPLATE_ID, personalisation={ 'subject': data['subject'], 'content': data['content'], 'summary': data['summary'], 'report': prepare_upload(f), 'signature': data['signature'] } ) os.remove(FILE_NAME)
def send_requestor_email(request_id): print('Sending mail') if Request.objects.get(id=request_id).rejected: status = 'has been rejected' rejection_reason = ', because: ' + Request.objects.get( id=request_id).rejected_reason else: status = 'is being reviewed' rejection_reason = '.' approver, requestor, user, reason, team_name, items_to_approve, sc = get_approval_details( request_id) attention_for = get_username(requestor) approver = get_username(approver) user = get_username(user) emailaddr = get_test_email_addreess(requestor) notifications_client = NotificationsAPIClient(settings.GOV_NOTIFY_API_KEY) notifications_client.send_email_notification( email_address=emailaddr, template_id=settings.EMAIL_REQUESTOR_UUID, personalisation={ 'name': attention_for, 'approver': approver, 'request_id': request_id, 'user': user, 'status': status, 'services': items_to_approve, 'rejection_reason': rejection_reason } )
def notify_about_changes(self, request: HttpRequest, person: Person) -> None: editor = request.user.profile if editor == person: return None context = { "profile_name": person.full_name, "editor_name": editor.full_name, "profile_url": request.build_absolute_uri( reverse("profile-view", kwargs={"profile_slug": person.slug})), } if settings.APP_ENV in ("local", "test"): logger.info(NOTIFY_ABOUT_CHANGES_LOG_MESSAGE.format(**context)) return notification_client = NotificationsAPIClient( settings.GOVUK_NOTIFY_API_KEY) notification_client.send_email_notification( person.email, settings.PROFILE_EDITED_EMAIL_TEMPLATE_ID, personalisation=context, )
def test_integration(): client = NotificationsAPIClient( base_url=os.environ['NOTIFY_API_URL'], api_key=os.environ['API_KEY'] ) client_using_team_key = NotificationsAPIClient( base_url=os.environ['NOTIFY_API_URL'], api_key=os.environ['API_SENDING_KEY'] ) sms_template_id = os.environ['SMS_TEMPLATE_ID'] sms_sender_id = os.environ['SMS_SENDER_ID'] email_template_id = os.environ['EMAIL_TEMPLATE_ID'] email_reply_to_id = os.environ['EMAIL_REPLY_TO_ID'] letter_template_id = os.environ['LETTER_TEMPLATE_ID'] assert sms_template_id assert sms_sender_id assert email_template_id assert email_reply_to_id version_number = 1 sms_id = send_sms_notification_test_response(client) sms_with_sender_id = send_sms_notification_test_response(client_using_team_key, sms_sender_id) email_id = send_email_notification_test_response(client) email_with_reply_id = send_email_notification_test_response(client, email_reply_to_id) letter_id = send_letter_notification_test_response(client) precompiled_letter_id = send_precompiled_letter_notification_test_response(client) precompiled_letter_with_postage_id = send_precompiled_letter_notification_set_postage_test_response(client) get_notification_by_id(client, sms_id, SMS_TYPE) get_notification_by_id(client, sms_with_sender_id, SMS_TYPE) get_notification_by_id(client, email_id, EMAIL_TYPE) get_notification_by_id(client, email_with_reply_id, EMAIL_TYPE) get_notification_by_id(client, letter_id, LETTER_TYPE) get_notification_by_id(client, precompiled_letter_id, LETTER_TYPE) get_notification_by_id(client, precompiled_letter_with_postage_id, LETTER_TYPE) get_all_notifications(client) get_template_by_id(client, sms_template_id, SMS_TYPE) get_template_by_id(client, email_template_id, EMAIL_TYPE) get_template_by_id(client, letter_template_id, LETTER_TYPE) get_template_by_id_and_version(client, sms_template_id, version_number, SMS_TYPE) get_template_by_id_and_version(client, email_template_id, version_number, EMAIL_TYPE) post_template_preview(client, sms_template_id, SMS_TYPE) post_template_preview(client, email_template_id, EMAIL_TYPE) get_all_templates(client) get_all_templates_for_type(client, EMAIL_TYPE) get_all_templates_for_type(client, SMS_TYPE) get_pdf_for_letter(client, letter_id) get_pdf_for_letter(client, precompiled_letter_id) if (os.environ['INBOUND_SMS_QUERY_KEY']): get_received_text_messages() print("notifications-python-client integration tests are successful")
def notify_about_deletion(self, person: Person, deleted_by: User) -> None: if deleted_by == person.user: return None # Find a the most suitable email. email = ((person.user and person.user.email) or person.contact_email or person.email) # If we can't find one, return. if not email: return None context = { "profile_name": person.full_name, "editor_name": deleted_by.get_full_name(), } if settings.APP_ENV in ("local", "test"): logger.info(f"{person.full_name}'s profile was deleted") return notification_client = NotificationsAPIClient( settings.GOVUK_NOTIFY_API_KEY) notification_client.send_email_notification( email, settings.PROFILE_DELETED_EMAIL_TEMPLATE_ID, personalisation=context, )
def send_activated_email(to: str, user: str, email: str, admin: str): if config.auth.internal.signup.notify.base_url is not None: nc = NotificationsAPIClient( config.auth.internal.signup.notify.api_key, base_url=config.auth.internal.signup.notify.base_url) nc.send_email_notification( to, config.auth.internal.signup.notify.activated_template, personalisation={ "fqdn": config.ui.fqdn, "user": user, "admin": admin, "email": email }) else: message = dedent(f""" The following account was activated on {config.ui.fqdn}. Username: {user} Email: {email} The account was activated by: {admin} Login at https://{config.ui.fqdn}/login.html """) title = f"Account for {user} now active on {config.ui.fqdn}" send_email(title, message, to)
def page_problem_found(request): message_sent = False if request.method == "POST": form = PageProblemFoundForm(request.POST) if form.is_valid(): page_url = form.cleaned_data["page_url"] trying_to = form.cleaned_data["trying_to"] what_went_wrong = form.cleaned_data["what_went_wrong"] notification_client = NotificationsAPIClient( settings.GOVUK_NOTIFY_API_KEY) message_sent = notification_client.send_email_notification( email_address=settings.SUPPORT_REQUEST_EMAIL, template_id=settings.PAGE_PROBLEM_EMAIL_TEMPLATE_ID, personalisation={ "user_name": request.user.get_full_name(), "user_email": request.user.email, "page_url": page_url, "trying_to": trying_to, "what_went_wrong": what_went_wrong, }, ) else: form = PageProblemFoundForm() return TemplateResponse( request, "core/page_problem_found.html", { "form": form, "message_sent": message_sent }, )
def generate_s3_and_send_email( barrier_ids: List[int], s3_filename: str, email: str, first_name: str, field_titles: Dict[str, str], ) -> None: queryset = Barrier.objects.filter(id__in=barrier_ids) serializer = BarrierCsvExportSerializer(queryset, many=True) # save the download event in the database BarrierSearchCSVDownloadEvent.objects.create( email=email, barrier_ids=",".join(barrier_ids), ) presigned_url = generate_and_upload_to_s3(s3_filename, field_titles, serializer) client = NotificationsAPIClient(settings.NOTIFY_API_KEY) client.send_email_notification( email_address=email, template_id=settings.NOTIFY_GENERATED_FILE_ID, personalisation={ "first_name": first_name.capitalize(), "file_name": s3_filename, "file_url": presigned_url, }, )
def send_authorize_email(to: str, user: str, email: str): if config.auth.internal.signup.notify.base_url is not None: nc = NotificationsAPIClient( config.auth.internal.signup.notify.api_key, base_url=config.auth.internal.signup.notify.base_url) nc.send_email_notification( to, config.auth.internal.signup.notify.authorization_template, personalisation={ "fqdn": config.ui.fqdn, "user": user, "email": email }) else: message = dedent(f""" The following user has created an account and is waiting that his account gets activated. User: {user} Email: {email} You can browse to the link below to activate the account: https://{config.ui.fqdn}/admin/users.html """) title = f"A new {config.ui.fqdn} user is waiting for your authorization" send_email(title, message, to)
def send_reset_email(to: str, reset_id: str): if config.auth.internal.signup.notify.base_url is not None: nc = NotificationsAPIClient( config.auth.internal.signup.notify.api_key, base_url=config.auth.internal.signup.notify.base_url) nc.send_email_notification( to, config.auth.internal.signup.notify.password_reset_template, personalisation={ "fqdn": config.ui.fqdn, "reset_id": reset_id }) else: message = dedent(f""" We have received a request to have your password reset for {config.ui.fqdn}. To reset your password, please visit the link below: https://{config.ui.fqdn}/reset.html?reset_id={reset_id} If you did not make this request, you can safely ignore this email and your password will remain the same. """) title = f"Password reset request for {config.ui.fqdn}" send_email(title, message, to)
def send_dataset_update_emails(update_emails_data_environment_variable): if update_emails_data_environment_variable not in os.environ: raise ValueError( f"Could not find data in environment for `{update_emails_data_environment_variable}`" ) dataset_info = json.loads( os.environ[update_emails_data_environment_variable]) dataset_url = dataset_info['dataset_url'] dataset_name = dataset_info['dataset_name'] emails = dataset_info['emails'] client = NotificationsAPIClient(os.environ['NOTIFY_API_KEY']) logger.info( f"Sending `dataset updated` emails to subscribers for " f"this pipeline (`{update_emails_data_environment_variable}`).") for email in emails: client.send_email_notification( email_address=email, template_id=os.environ['NOTIFY_TEMPLATE_ID__DATASET_UPDATED'], personalisation={ "dataset_name": dataset_name, "dataset_url": dataset_url }, )
def send_default_investment_email(pir_report): notifications_client = NotificationsAPIClient(settings.GOV_NOTIFY_API_KEY) notifications_client.send_email_notification( email_address=pir_report.email, template_id=settings.DEFAULT_EMAIL_UUID, personalisation={ 'name': pir_report.name, })
def get_received_text_messages(): client = NotificationsAPIClient( base_url=os.environ['NOTIFY_API_URL'], api_key=os.environ['INBOUND_SMS_QUERY_KEY']) response = client.get_received_texts() validate(response, get_inbound_sms_response) assert len(response['received_text_messages']) > 0
def send_email(user, saved_searches): client = NotificationsAPIClient(settings.NOTIFY_API_KEY) client.send_email_notification( email_address=user.email, template_id=settings.NOTIFY_SAVED_SEARCHES_TEMPLATE_ID, personalisation={ "first_name": user.first_name, "saved_searches": get_saved_searches_markdown(saved_searches), "dashboard_link": settings.DMAS_BASE_URL, })
class NotifyService: """ Service that wraps the Government of Canada Notifications API """ def __init__(self, api_key=None, end_point=None): self.client = None if api_key is None or end_point is None: logging.info("Notifications disabled, no api key or end point specified.") else: self.client = NotificationsAPIClient(api_key, base_url=end_point) def send_email(self, address, template_id, details): """ Send a new email using the GC notification client Args: address: The email address template_id: The id of the template to use details: Dictionary of personalization variables """ if self.client: try: self.client.send_email_notification( email_address=address, template_id=template_id, personalisation=details, ) except HTTPError as e: raise Exception(e) else: logging.info(f"Notifications disabled. Otherwise would email: {address}.") def send_sms(self, phone_number, template_id, details): """ Send a new SMS using the GC notification client Args: phone_number: The phone number to send to template_id: The id of the template to use details: Dictionary of personalization variables """ if self.client: try: self.client.send_sms_notification( phone_number=phone_number, template_id=template_id, personalisation=details, ) except HTTPError as e: raise Exception(e) else: logging.info( f"Notifications disabled. Otherwise would text to: {phone_number}." )
def get_notification_by_to_field(template_id, api_key, sent_to, statuses=None): client = NotificationsAPIClient(base_url=config['notify_api_url'], api_key=api_key) resp = client.get('v2/notifications') for notification in resp['notifications']: t_id = notification['template']['id'] to = notification['email_address'] or notification['phone_number'] if t_id == template_id and to == sent_to and ( not statuses or notification['status'] in statuses): return notification['body'] return ''
def send_email(template_id, email_address, personalisation=None, reference=None): client = NotificationsAPIClient(settings.NOTIFY_API_KEY) client.send_email_notification( template_id=template_id, email_address=email_address, personalisation=personalisation, reference=reference, )
def get_notification_via_api(service_id, template_id, api_key, sent_to): client = NotificationsAPIClient(base_url=Config.NOTIFY_API_URL, service_id=service_id, api_key=api_key) resp = client.get("notifications", params={"include_jobs": True}) for notification in resp["notifications"]: t_id = notification["template"]["id"] to = notification["to"] status = notification["status"] if t_id == template_id and to == sent_to and status in ["sending", "delivered"]: return notification["body"] message = "Could not find notification with template {} to {} with a status of sending or delivered".format( template_id, sent_to ) raise RetryException(message)
def send_barrier_inactivity_reminders(): """ Get list of all barriers with modified_on and activity_reminder_sent dates older than 6 months For each barrier sent a reminder notification to the barrier owner """ # datetime 6 months ago inactivity_theshold_date = timezone.now() - timedelta( days=settings.BARRIER_INACTIVITY_THESHOLD_DAYS) repeat_reminder_theshold_date = timezone.now() - timedelta( days=settings.BARRIER_REPEAT_REMINDER_THESHOLD_DAYS) barriers_needing_reminder = Barrier.objects.filter( modified_on__lt=inactivity_theshold_date).filter( Q(activity_reminder_sent__isnull=True) | Q(activity_reminder_sent__lt=repeat_reminder_theshold_date)) for barrier in barriers_needing_reminder: recipient = barrier.barrier_team.filter(role="Owner").first() if not recipient: recipient = barrier.barrier_team.filter(role="Reporter").first() if not recipient: logger.warn(f"No recipient found for barrier {barrier.id}") continue if not recipient.user: logger.warn( f"No user found for recipient {recipient.id} and barrier {barrier.id}" ) continue recipient = recipient.user full_name = f"{recipient.first_name} {recipient.last_name}" client = NotificationsAPIClient(settings.NOTIFY_API_KEY) client.send_email_notification( email_address=recipient.email, template_id=settings.BARRIER_INACTIVITY_REMINDER_NOTIFICATION_ID, personalisation={ "barrier_title": barrier.title, "barrier_url": f"{settings.DMAS_BASE_URL}/barriers/{barrier.id}/", "full_name": full_name, "barrier_created_date": barrier.created_on.strftime("%d %B %Y"), }, ) barrier.activity_reminder_sent = timezone.now() barrier.save()
def send_email(to, subject, name, body, template): personalisation = { 'subject': subject, 'name': name, 'body': body } notify_client = NotificationsAPIClient(current_app.config['NOTIFY_API_KEY']) response = notify_client.send_email_notification( email_address=to, template_id=templates[template], personalisation=personalisation, reference=None )
def _send(): notifications_client = NotificationsAPIClient(api_key) submission_date = datetime.now() read_close_date = submission_date + relativedelta(months=6) response = notifications_client.send_email_notification( email_address=email_address, template_id=email_template_id, personalisation={ "first_name": form.cleaned_data["name"], "registration_mark": form.cleaned_data["reg"], "submission_date": submission_date.strftime("%d %B %Y"), "read_close_date": read_close_date.strftime("%d %B %Y"), "survey_url": "https://example.com/xyz" }) return response["id"]
def test_integration(): client = NotificationsAPIClient(base_url=os.environ['NOTIFY_API_URL'], api_key=os.environ['API_KEY']) sms_template_id = os.environ['SMS_TEMPLATE_ID'] email_template_id = os.environ['EMAIL_TEMPLATE_ID'] version_number = 1 sms_id = send_sms_notification_test_response(client) email_id = send_email_notification_test_response(client) get_notification_by_id(client, sms_id, SMS_TYPE) get_notification_by_id(client, email_id, EMAIL_TYPE) get_all_notifications(client) get_template_by_id(client, sms_template_id, SMS_TYPE) get_template_by_id(client, email_template_id, EMAIL_TYPE) get_template_by_id_and_version(client, sms_template_id, version_number, SMS_TYPE) get_template_by_id_and_version(client, email_template_id, version_number, EMAIL_TYPE) post_template_preview(client, sms_template_id, SMS_TYPE) post_template_preview(client, email_template_id, EMAIL_TYPE) get_all_templates(client) get_all_templates_for_type(client, EMAIL_TYPE) get_all_templates_for_type(client, SMS_TYPE) print("notifications-python-client integration tests are successful")
def send_mail(self, template_prefix, email, context): notifications_client = NotificationsAPIClient( settings.NOTIFY_API_KEY, base_url=settings.NOTIFY_ENDPOINT) try: notifications_client.send_email_notification( email_address=context.get("email"), template_id=settings.INVITATION_EMAIL_TEMPLATE_ID.get( context.get("language") or "en"), personalisation={ "url": context.get("invite_url"), "admin_email": context.get("inviter").email, }, ) except HTTPError as e: raise Exception(e)
def _initialise_clients(self): clients = {} for service_name, api_key_setting_name in NOTIFY_KEYS.items(): api_key = getattr(settings, api_key_setting_name) if api_key: clients[service_name] = NotificationsAPIClient(api_key) else: # Mocking the client when we don't have an API key set gives us a dummy client. # It has some benefits: # 1) It allows developers to use local copies without needing to find API # credentials. # 2) It means we do not need to complicate the client and provide a separate # execution path when the API key is unset. client = mock.Mock(spec_set=NotificationsAPIClient) client.send_email_notification.return_value = {'id': 'abc123'} clients[service_name] = client warnings.warn( f'`settings.{api_key_setting_name}` not specified therefore notifications ' "will be mocked. You might want to change this if it's not a testing or " 'development environment.', RuntimeWarning, stacklevel=2, ) self.clients = clients
def notify(self, django_user, barrier): barrier_obj = Barrier.objects.get(id=barrier) client = NotificationsAPIClient(settings.NOTIFY_API_KEY) barrier_url = urllib.parse.urljoin( settings.FRONTEND_DOMAIN, f"/barriers/{barrier}/action_plan" ) client.send_email_notification( email_address=django_user.email, template_id=settings.NOTIFY_ACTION_PLAN_USER_SET_AS_OWNER_ID, personalisation={ "first_name": django_user.first_name, "mentioned_by": f"{django_user.first_name} {django_user.last_name}", "barrier_number": barrier_obj.code, "barrier_name": barrier_obj.title, "barrier_url": barrier_url, }, )
def _deliver_token(self, token): self._validate_config() notifications_client = NotificationsAPIClient( settings.OTP_NOTIFY_API_KEY, base_url=settings.OTP_NOTIFY_ENDPOINT) try: response = notifications_client.send_sms_notification( phone_number=self.number, template_id=settings.OTP_NOTIFY_TEMPLATE_ID, sms_sender_id=settings.OTP_NOTIFY_SENDER_ID, personalisation={'token': token}, ) except HTTPError as e: logger.exception(e.message) raise Exception(e.message[0].get("message")) return response