Send Password Reset Link to an Email Registered in user_metadata

Overview

This article explains how to send password reset links to an email that is registered under user_metadata.

Applies To

  • Custom Email Provider
  • Actions

Solution

There is no feature available natively in Auth0 that can send password reset links to an email that is registered under user_metadata; however, it is possible to configure a custom action to run for an email message provider to achieve this functionality. This can be done through a Custom Email Provider.

NOTE: To use this solution, it is required that all emails sent, not only the password reset links, are managed through this script

To turn on this setting:

  1. Go to the Auth0 Dashboard and select Branding > Email Provider.
  2. Enable the Use my own email provider Toggle.
  3. In the Email Provider Section, select Custom Provider.

    Here is an example of custom code using Mailtrap. Please note: The following code is just for demonstration purposes. Any other customization is up to specific requirements or use cases:
exports.onExecuteCustomEmailProvider = async (event, api) => {
  const nodemailer = require('nodemailer');

  // Mailtrap Credentials
  const host = event.secrets.MAILTRAP_HOST;
  const port = event.secrets.MAILTRAP_PORT;
  const user = event.secrets.MAILTRAP_USER;
  const pass = event.secrets.MAILTRAP_PASS;
  const fromAddress = event.secrets.EMAIL_FROM;


  // Custom Email
  const metadataEmail = event.user.user_metadata && event.user.user_metadata.email;
  const originalRecipient = event.user.email;

  const finalRecipient = metadataEmail || originalRecipient;

  if (!finalRecipient) {
    console.log(`No valid recipient found for user ${event.user.user_id}. Original: ${originalRecipient}, Metadata: ${metadataEmail}. Skipping email.`);
    return;
  }

  // Email Sending Configuration
  const subject = event.notification.subject;
  const htmlBody = event.notification.html;

  const transporter = nodemailer.createTransport({
    host: host,
    port: parseInt(port, 10),
    secure: parseInt(port, 10) === 465,
    auth: {
      user: user,
      pass: pass,
    },
  });

  const mailOptions = {
    from: fromAddress,
    to: finalRecipient,
    subject: subject,
    html: htmlBody,
  };

  try {
    console.log(`Attempting to send email type '${event.notification.message_type}' to Mailtrap (intended for ${finalRecipient}).`);
    const info = await transporter.sendMail(mailOptions);
  } catch (error) {
    console.error(`Error sending email via Mailtrap (intended for ${finalRecipient}):`, error.toString());
  }
  return;
};