Luca
Luca

Reputation: 1279

Cognito send confirmation email using custom email

There's a way to send an email other than the one specified in the "Message customisation" tab on Cognito user pool? I would like to use different email based on some parameters.

E.g.

[email protected] for verification email

[email protected] for welcome email

Upvotes: 2

Views: 7205

Answers (2)

James Irwin
James Irwin

Reputation: 1191

If you want to handle all emails yourself, you can specify this with a CustomEmailSender Lambda. This trigger isn't currently available through the AWS Console, but you can specify it with the CLI or CDK/CloudFormation. See the docs here.

Those docs are pretty terrible though. The gist is that you'll be given a code property on the event, which is a base64-encoded blob that was encrypted with the KMS key you specified on your user pool. Depending on the triggering event, this is the verification code, temporary password, etc, generated by Cognito. Here's a simplified version of what my Lambda looks like:

import { buildClient, CommitmentPolicy, KmsKeyringNode } from '@aws-crypto/client-node';

const { decrypt } = buildClient(CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT);

const kmsKeyring = new KmsKeyringNode({
    keyIds: [process.env.COGNITO_EMAILER_KEY_ARN]
});

export async function lambdaHandler(event, context) {
  try {
    let payload = '';

    if (event.request.code) {
      const { plaintext, messageHeader } = await decrypt(
        kmsKeyring,
        Buffer.from(event.request.code, "base64")
      );

      if (event.userPoolId !== messageHeader.encryptionContext["userpool-id"]) {
        console.error("Encryption context does not match expected values!");
        return;
      }

      payload = plaintext.toString();
    }

    let messageHtml = "";

    switch (event.triggerSource) {
      case "CustomEmailSender_SignUp": {
        const verificationCode = payload;

        messageHtml = `<p>Use this code to verify your email: ${verificationCode}</p>`;

        break;
      }
      case "CustomEmailSender_AdminCreateUser":
      case "CustomEmailSender_ResendCode": {
        const tempPassword = payload;

        messageHtml = `<p>Your temporary password is ${tempPassword}</p>`;

        break;
      }
      default: {
        console.warn("unhandled trigger:", event.triggerSource);
        return;
      }
    }

    await sendEmail({
      subject: "Automated message",
      to: event.request.userAttributes.email,
      messageHtml,
    });

    return true;
  } catch (err) {
    console.error(err.message);
    process.exit(1);
  }
}

Upvotes: 4

Chris Burke
Chris Burke

Reputation: 61

You can go to the general settings in Cognito then click on triggers. There you can select Post Confirmation lambda function(this example in node) to send the email. In the lambda function you can make the subject whatever you like and change from email address.

var aws = require('aws-sdk');
var ses = new aws.SES();

exports.handler = function(event, context) {
  console.log(event);

  if (event.request.userAttributes.email) {
    // Pull another attribute if you want
    sendEmail(event.request.userAttributes.email, 
      "Congratulations "+event.userName+", you have been registered!"
      , function(status) {
         context.done(null, event);
      });
    } else {
      // Nothing to do, the user's email ID is unknown
      console.log("Failed");
      context.done(null, event);
    }
  };

  function sendEmail(to, body, completedCallback) {
    var eParams = {
      Destination: {
        ToAddresses: [to]
      },
      Message: {
        Body: {
          Text: {
            Data: body
          }
        },
        Subject: {
          Data: "Welcome to My Service!"
        }
      },
      Source: "[email protected]"
    };

    var email = ses.sendEmail(eParams, function(err, data){
      if (err) {
        console.log(err);
      } else {
        console.log("===EMAIL SENT===");
      }

      completedCallback('Email sent');
    });

    console.log("EMAIL CODE END");
  };

You will also have to set up SES.

Upvotes: 6

Related Questions