При отправке пользовательского сообщения электронной почты для триггера CustomMessage_AdminCreateUser
я успешно изменяю атрибут emailSubject
в событии, полученном от Amazon Cognito, но не могу изменить атрибут emailMessage
.
Письмо, отправленное из Cognito, содержит правильную настроенную тему, но сообщение вообще не настроено, и оно всегда задается в настройках пула Cognito.
Лямбда-обработчик, который обрабатывает событие, полученное от Cognito, успешно настраивает сообщение для этих триггеров:
CustomMessage_SignUp
CustomMessage_ResendCode
CustomMessage_ForgotPassword
Но я не могу заставить его работать (по крайней мере, не полностью) для CustomMessage_AdminCreateUser
триггера.
Я попытался установить для email_verified
пользовательского атрибута значение true
, чтобы проверить, зависит ли этот атрибут от успешной отправки настроенной почты созданному пользователю. Кроме того, я попытался запустить лямбду в контейнере Docker, чтобы увидеть результат конечного события, возвращаемого в Cognito, но это событие содержит правильные данные, как тема электронной почты, так и сообщение электронной почты были настроены.
def lambda_handler(event, context):
if event['userPoolId'] == os.getenv('cognitoPoolId'):
if CustomMessageTriggerEnum.has_value(event.get('triggerSource')):
custom_message_trigger = CustomMessageTriggerEnum(event.get('triggerSource'))
if custom_message_trigger == CustomMessageTriggerEnum.CustomMessageAdminCreateUser:
custom_message_trigger = CustomMessageAdminCreateUser(event)
else:
return None
custom_response = custom_message_trigger.get_custom_response(
custom_message_trigger.ACTION,
custom_message_trigger.EMAIL_SUBJECT,
custom_message_trigger.EMAIL_MESSAGE
)
event = custom_message_trigger.set_custom_response(**custom_response)
return event
class CustomMessageAdminCreateUser(BaseCustomMessageTrigger):
""" Custom message admin create user trigger """
ACTION = "changepassword"
EMAIL_SUBJECT = "Welcome to {service}"
EMAIL_MESSAGE = "Your account has been created. <a href='{0}'>Click here</a> to set your password and start using {service}."
def __init__(self, event):
super().__init__(event)
class BaseCustomMessageTrigger():
""" Base custom message trigger """
def __init__(self, event):
self.event = event
def get_custom_response(self, action, email_subject, email_message):
""" Gets custom response params as dictionary """
request = self.event.get('request')
custom_response = {}
url = self.get_url(
action=action,
code=request.get('codeParameter'),
email=urlencode({'email': request['userAttributes'].get('email')})
)
custom_response['emailSubject'] = email_subject
custom_response['emailMessage'] = email_message.format(url)
return custom_response
def set_custom_response(self, **kwargs):
""" Updates the event response with provided kwargs """
response = self.event.get('response')
response.update(**kwargs)
return self.event
def get_url(self, action, code, email):
""" Used for constructing URLs. """
rawUrl = 'https://{0}/{1}?code={2}&{3}'
return rawUrl.format(domain, action, code, email)