WSO2 - IS - send a custom email template from identity server using a custom event handler

273 views Asked by At

I have tried using an approach as suggested in the below blog

https://is.docs.wso2.com/en/latest/develop/writing-a-custom-event-handler/

I have a requirement to send a custom email template when a user role is changed in the identity server.somehow I have figured out the event when we change the role. But I'm not getting a way to send a mail from a custom event handler. I would like to know if there is any other way to achieve this? Thanks in advance

1

There are 1 answers

0
senthalan On

All you need to do is trigger a TRIGGER_NOTIFICATION event from your event handler with some properties, then existing implementation of that event will get the template ID and fill the placeholders with the values passed in the event and send out the mail.

This is be a sample code segment.

        String eventName = IdentityEventConstants.Event.TRIGGER_NOTIFICATION;

        HashMap<String, Object> properties = new HashMap<>();
        properties.put(IdentityEventConstants.EventProperty.USER_NAME, user.getUserName());
        properties.put(IdentityEventConstants.EventProperty.TENANT_DOMAIN, user.getTenantDomain());
        properties.put(IdentityEventConstants.EventProperty.USER_STORE_DOMAIN, user.getUserStoreDomain());
        properties.put("OLD_ROLE", oldRole);
        properties.put("NEW_ROLE", newRole);
        properties.put("TEMPLATE_TYPE", templateId);

        Event identityMgtEvent = new Event(eventName, properties);
        try {
            NotificationFunctionServiceHolder.getInstance().getIdentityEventService().handleEvent(identityMgtEvent);
        } catch (IdentityEventException | NotificationRuntimeException e) {
            LOG.error(String.format("Error when sending notification of template %s to user %s", templateId, user
                    .toFullQualifiedUsername()), e);
            
        }
        

Here you need to replace user, oldRole, newRole and templateId. In template management, you need to create a new email template with this templateId and there you can design the email with these placeholders(OLD_ROLE, NEW_ROLE, for other placeholders you can refer to the existing templates.).

You can find the event handler implementation of TRIGGER_NOTIFICATION here for any reference about this.