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)
Exemple #2
0
    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)
Exemple #3
0
    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_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
Exemple #5
0
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
            },
        )
Exemple #6
0
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)
Exemple #7
0
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_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
        }
    )
Exemple #9
0
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_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
        }
    )
Exemple #12
0
    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,
        )
Exemple #13
0
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,
        })
Exemple #14
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,
        })
Exemple #15
0
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 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,
    )
Exemple #17
0
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()
Exemple #18
0
    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)
Exemple #19
0
    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)
Exemple #20
0
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 send_completed_email(completed_tasks):
    print('Sending mail')
    notifications_client = NotificationsAPIClient(settings.GOV_NOTIFY_API_KEY)
    out = defaultdict(list)
    for item in completed_tasks:
        service_str = item['services__service_name'] + \
            ', link to docs: ' + \
            Services.objects.get(service_name=item['services__service_name']).service_docs + \
            ', service url: ' + \
            Services.objects.get(service_name=item['services__service_name']).service_url
        out[item['request_id']].append(service_str)

    for x in out:
        confirmation_user = Request.objects.get(id=x).user_email
        confirmation_requestor = Request.objects.get(id=x).requestor

        if out[x][0].partition(',')[0] in ['google analytics', 'github', 'ukgov paas']:
            services = '[' + out[x][0] + ' - ' + RequestItem.objects.get(
                request_id=x, services__service_name=out[x][0]).additional_info + ']'
        else:
            services = out[x]

        attention_for = get_username(confirmation_user)
        emailaddr = get_test_email_addreess(confirmation_user)

        notifications_client.send_email_notification(
            email_address=emailaddr,
            template_id=settings.EMAIL_COMPLETED_UUID,
            personalisation={
                'who_got_access': 'You have',
                'name': attention_for,
                'services': services
            }
        )

        if confirmation_requestor != confirmation_user:
            attention_for = get_username(confirmation_requestor)
            emailaddr = get_test_email_addreess(confirmation_requestor)
            user_given_access = get_username(confirmation_user)

            notifications_client.send_email_notification(
                email_address=emailaddr,
                template_id=settings.EMAIL_COMPLETED_UUID,
                personalisation={
                    'who_got_access': user_given_access + ' has',
                    'name': attention_for,
                    'services': services})
Exemple #22
0
    def send_mail(self, language):
        notifications_client = NotificationsAPIClient(
            settings.NOTIFY_API_KEY, base_url=settings.NOTIFY_ENDPOINT)

        try:
            notifications_client.send_email_notification(
                email_address=self.admin.email,
                template_id=settings.BACKUP_CODE_ADMIN_EMAIL_TEMPLATE_ID.get(
                    language or "en"),
                personalisation={
                    "name": self.admin.name,
                    "user_email": self.user.email,
                    "user_name": self.user.name,
                },
            )
        except HTTPError as e:
            raise Exception(e)
def send_accounts_creator_close_email(creator, offboard, services):
    print('Sending mail to', creator)

    notifications_client = NotificationsAPIClient(settings.GOV_NOTIFY_API_KEY)
    attention_for = get_username(creator)
    offboard = get_username(offboard)
    emailaddr = get_test_email_addreess(creator)

    notifications_client.send_email_notification(
        email_address=emailaddr,
        template_id=settings.EMAIL_OFFBOARD_UUID,
        personalisation={
            'creator': attention_for,
            'offboard': offboard,
            'services': services
        }
    )
Exemple #24
0
 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 send_accounts_creator_email(request_id):
    print('Sending mail')
    request_approve = RequestItem.objects.values_list('services_id').filter(
        request_id__in=request_id)
    creators_id = AccountsCreator.objects.values_list('email', flat=True).filter(
        services__in=request_approve)
    notifications_client = NotificationsAPIClient(settings.GOV_NOTIFY_API_KEY)
    ras_url = 'https://' + settings.DOMAIN_NAME + '/action-requests/'

    for creator in set(creators_id):
        print('emailing: ')
        print(creator)
        attention_for = get_username(creator)
        emailaddr = get_test_email_addreess(creator)

        notifications_client.send_email_notification(
            email_address=emailaddr,
            template_id=settings.EMAIL_ACTIVATE_UUID,
            personalisation={
                'name': attention_for,
                'ras_url': ras_url
            }
        )
def send_end_user_email(request_id):
    print('Sending mail')
    approver, requestor, user, reason, team_name, items_to_approve, sc = get_approval_details(
        request_id)
    ras_url = 'https://' + settings.DOMAIN_NAME + '/request-status/'
    attention_for = get_username(user)
    requestor = get_username(requestor)
    approver = get_username(approver)
    emailaddr = get_test_email_addreess(user)

    notifications_client = NotificationsAPIClient(settings.GOV_NOTIFY_API_KEY)
    notifications_client.send_email_notification(
        email_address=emailaddr,
        template_id=settings.EMAIL_ENDUSER_UUID,
        personalisation={
            'name': attention_for,
            'requester': requestor,
            'approver': approver,
            'request_id': request_id,
            'ras_url': ras_url,
            'services': items_to_approve
        }
    )
Exemple #27
0
    def left_dit(self, request: HttpRequest, person: Person,
                 reported_by: Person, comment: str) -> None:
        """Submit that the given person has left the DIT.

        Args:
            request: The associated HTTP request.
            person: The person who has left the DIT.
            reported_by: Who reported that the person has left.
            comment: A comment from the reporter about the request.
        """
        context = {
            "profile_name":
            person.full_name,
            "profile_url":
            request.build_absolute_uri(
                reverse("profile-view", kwargs={"profile_slug": person.slug})),
            "reporter_name":
            reported_by.full_name,
            "reporter_email":
            reported_by.preferred_email,
            "comment":
            comment,
        }

        if settings.APP_ENV in ("local", "test"):
            logger.info(LEFT_DIT_LOG_MESSAGE.format(**context))

            return

        notification_client = NotificationsAPIClient(
            settings.GOVUK_NOTIFY_API_KEY)
        notification_client.send_email_notification(
            settings.PROFILE_DELETION_REQUEST_EMAIL,
            settings.PROFILE_DELETION_REQUEST_EMAIL_TEMPLATE_ID,
            personalisation=context,
        )
Exemple #28
0
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
    )
Exemple #29
0
 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"]
Exemple #30
0
def send_email(template_id,
               email_address,
               personalisation=None,
               reference=None):
    client = NotificationsAPIClient(settings.NOTIFY_API_KEY)

    response = client.send_email_notification(
        template_id=template_id,
        email_address=email_address,
        personalisation=personalisation,
        reference=reference,
    )
    # pylint: disable=unsupported-membership-test
    if "id" in response:
        # pylint: disable=unsubscriptable-object
        return response["id"]
    else:
        raise EmailSendFailureException(response)