生成电子邮件操作链接

移动应用有时需要与用户进行交互,并通过发送电子邮件来提示用户执行某些操作。

Firebase 客户端 SDK 让您能够向用户发送包含相关链接的电子邮件,用户可以使用这些链接进行密码重设、电子邮件地址验证和基于电子邮件的登录。这些基于模板的电子邮件由 Google 发送,可以进行有限的定制。

如果您希望改用自己的电子邮件模板和自己的电子邮件递送服务,则可以参阅本页面;本页面介绍了如何使用 Firebase Admin SDK 以编程方式为上述流程生成操作链接,然后将这些链接包含在要发送给用户的电子邮件中。

这样做具有以下优势:

  • 自定义电子邮件模板。这包括添加新样式、采用自定义品牌标识、更改措辞和徽标、以名字而不是全名称呼用户等功能。
  • 根据情景采用不同的模板。例如,如果用户正在验证其电子邮件地址以订阅简报,则可能需要在电子邮件内容中提供相关背景信息。另一个示例是电子邮件链接登录:这可以由同一用户触发,也可以由另一位用户的邀请触发,因而需要将相关背景信息包含在电子邮件中。
  • 本地化自定义电子邮件模板。
  • 能够从安全的服务器环境生成链接。
  • 能够自定义链接的打开方式(通过移动应用还是浏览器)以及额外状态信息的传递方式,等等。
  • 能够在构建电子邮件操作链接时自定义用于移动应用流的移动链接网域。

初始化 ActionCodeSettings

您可能需要初始化 ActionCodeSettings 实例,才能生成电子邮件操作链接。

ActionCodeSettings 允许您通过一个在用户点击电子邮件链接后转到的接续网址来传递更多状态信息。这还能让用户在完成操作后返回到应用中。此外,您还可以指定是直接从安装的移动应用处理电子邮件操作链接,还是从浏览器处理。

对于要通过移动应用打开的链接,您需要执行一些任务,才能从移动应用中检测到这些链接。请参阅有关如何为电子邮件操作配置移动链接的说明。

如需初始化 ActionCodeSettings 实例,请提供以下数据:

参数 类型 说明
url 字符串

设置在不同场景中具有不同含义的链接(状态/接续网址):

  • 当在 Web 操作 widget 中处理链接时,此参数是 continueUrl 查询参数中的深层链接。
  • 当直接在应用中处理链接时,此参数是 Hosting 链接的深层链接中的 continueUrl 查询参数。
iOS ({bundleId: 字符串}|未定义) 设置 iOS 软件包 ID,以帮助 Firebase Authentication 确定是否应创建在 Apple 设备上打开的仅限网页链接或移动链接
android ({packageName: 字符串, installApp:布尔值|未定义, minimumVersion: 字符串|未定义}|未定义) 设置 Android 软件包名称,以帮助 Firebase Authentication 确定是否应创建在 Android 设备上打开的仅限网页链接或移动链接
handleCodeInApp (布尔值|未定义) 决定电子邮件操作链接是优先在移动应用中打开还是优先作为网页链接打开。默认值为 false。当设置为 true 时,操作代码链接将以通用链接或 Android 应用链接的形式发送;如果用户已安装应用,该链接将在应用中打开。如果设置为 false,则系统会先将代码发送到 web widget,然后在接续时重定向到应用(如果已安装应用)。
linkDomain (字符串|未定义) 如果为项目定义了自定义 Hosting 链接网域,请指定在通过指定的移动应用打开链接时应使用哪个网域。否则,系统会自动选择默认网域(例如 PROJECT_ID.firebaseapp.com)。
dynamicLinkDomain (字符串|未定义) 已弃用。请勿指定此参数。

以下示例说明了如何发送先在移动应用中打开的电子邮件验证链接。深层链接将包含接续网址载荷 https://www.example.com/checkout?cartId=1234。使用的自定义 Hosting 链接网域是 custom-domain.com;必须配置该网域,才能将其与 Firebase Hosting 一起使用。

Node.js

const actionCodeSettings = {
  // URL you want to redirect back to. The domain (www.example.com) for
  // this URL must be whitelisted in the Firebase Console.
  url: 'https://www.example.com/checkout?cartId=1234',
  // This must be true for email link sign-in.
  handleCodeInApp: true,
  iOS: {
    bundleId: 'com.example.ios',
  },
  android: {
    packageName: 'com.example.android',
    installApp: true,
    minimumVersion: '12',
  },
  // FDL custom domain.
  dynamicLinkDomain: 'coolapp.page.link',
};

Java

ActionCodeSettings actionCodeSettings = ActionCodeSettings.builder()
    .setUrl("https://www.example.com/checkout?cartId=1234")
    .setHandleCodeInApp(true)
    .setIosBundleId("com.example.ios")
    .setAndroidPackageName("com.example.android")
    .setAndroidInstallApp(true)
    .setAndroidMinimumVersion("12")
    .setDynamicLinkDomain("coolapp.page.link")
    .build();

Python

action_code_settings = auth.ActionCodeSettings(
    url='https://www.example.com/checkout?cartId=1234',
    handle_code_in_app=True,
    ios_bundle_id='com.example.ios',
    android_package_name='com.example.android',
    android_install_app=True,
    android_minimum_version='12',
    dynamic_link_domain='coolapp.page.link',
)

Go

actionCodeSettings := &auth.ActionCodeSettings{
	URL:                   "https://www.example.com/checkout?cartId=1234",
	HandleCodeInApp:       true,
	IOSBundleID:           "com.example.ios",
	AndroidPackageName:    "com.example.android",
	AndroidInstallApp:     true,
	AndroidMinimumVersion: "12",
	DynamicLinkDomain:     "coolapp.page.link",
}

C#

var actionCodeSettings = new ActionCodeSettings()
{
    Url = "https://www.example.com/checkout?cartId=1234",
    HandleCodeInApp = true,
    IosBundleId = "com.example.ios",
    AndroidPackageName = "com.example.android",
    AndroidInstallApp = true,
    AndroidMinimumVersion = "12",
    DynamicLinkDomain = "coolapp.page.link",
};

如需了解详情,请参阅在电子邮件操作中传递状态

生成密码重设电子邮件链接

如需生成重设密码链接,请提供现有用户的电子邮件地址和可选的 ActionCodeSettings 对象。执行该操作将生成电子邮件操作链接。使用的电子邮件地址必须属于现有用户。

Node.js

// Admin SDK API to generate the password reset link.
const userEmail = 'user@example.com';
getAuth()
  .generatePasswordResetLink(userEmail, actionCodeSettings)
  .then((link) => {
    // Construct password reset email template, embed the link and send
    // using custom SMTP server.
    return sendCustomPasswordResetEmail(userEmail, displayName, link);
  })
  .catch((error) => {
    // Some error occurred.
  });

Java

String email = "user@example.com";
try {
  String link = FirebaseAuth.getInstance().generatePasswordResetLink(
      email, actionCodeSettings);
  // Construct email verification template, embed the link and send
  // using custom SMTP server.
  sendCustomEmail(email, displayName, link);
} catch (FirebaseAuthException e) {
  System.out.println("Error generating email link: " + e.getMessage());
}

Python

email = 'user@example.com'
link = auth.generate_password_reset_link(email, action_code_settings)
# Construct password reset email from a template embedding the link, and send
# using a custom SMTP server.
send_custom_email(email, link)

Go

email := "user@example.com"
link, err := client.PasswordResetLinkWithSettings(ctx, email, actionCodeSettings)
if err != nil {
	log.Fatalf("error generating email link: %v\n", err)
}

// Construct password reset template, embed the link and send
// using custom SMTP server.
sendCustomEmail(email, displayName, link)

C#

var email = "user@example.com";
var link = await FirebaseAuth.DefaultInstance.GeneratePasswordResetLinkAsync(
    email, actionCodeSettings);
// Construct email verification template, embed the link and send
// using custom SMTP server.
SendCustomEmail(email, displayName, link);

生成链接后,可以将其插入自定义密码重设电子邮件,然后使用自定义 SMTP 服务器通过电子邮件发送给相应的用户。

如果您没有使用默认的密码重设着陆页,而想要构建自己的自定义处理程序,请参阅创建自定义电子邮件操作处理程序

生成电子邮件验证链接

如需生成电子邮件验证链接,请提供现有用户的未验证电子邮件地址和可选的 ActionCodeSettings 对象。执行该操作将生成电子邮件操作链接。使用的电子邮件地址必须属于现有用户。

Node.js

// Admin SDK API to generate the email verification link.
const useremail = 'user@example.com';
getAuth()
  .generateEmailVerificationLink(useremail, actionCodeSettings)
  .then((link) => {
    // Construct email verification template, embed the link and send
    // using custom SMTP server.
    return sendCustomVerificationEmail(useremail, displayName, link);
  })
  .catch((error) => {
    // Some error occurred.
  });

Java

String email = "user@example.com";
try {
  String link = FirebaseAuth.getInstance().generateEmailVerificationLink(
      email, actionCodeSettings);
  // Construct email verification template, embed the link and send
  // using custom SMTP server.
  sendCustomEmail(email, displayName, link);
} catch (FirebaseAuthException e) {
  System.out.println("Error generating email link: " + e.getMessage());
}

Python

email = 'user@example.com'
link = auth.generate_email_verification_link(email, action_code_settings)
# Construct email from a template embedding the link, and send
# using a custom SMTP server.
send_custom_email(email, link)

Go

email := "user@example.com"
link, err := client.EmailVerificationLinkWithSettings(ctx, email, actionCodeSettings)
if err != nil {
	log.Fatalf("error generating email link: %v\n", err)
}

// Construct email verification template, embed the link and send
// using custom SMTP server.
sendCustomEmail(email, displayName, link)

C#

var email = "user@example.com";
var link = await FirebaseAuth.DefaultInstance.GenerateEmailVerificationLinkAsync(
    email, actionCodeSettings);
// Construct email verification template, embed the link and send
// using custom SMTP server.
SendCustomEmail(email, displayName, link);

生成链接后,可以将其插入自定义验证电子邮件,然后使用自定义 SMTP 服务器通过电子邮件发送给相应的用户。

如果您没有使用默认的电子邮件验证着陆页,而想要构建自己的自定义处理程序,请参阅创建自定义电子邮件操作处理程序

生成用于登录的电子邮件链接

您需要为 Firebase 项目启用电子邮件链接登录,才能使用该功能对用户进行身份验证。

如需生成登录链接,请提供用户的电子邮件地址和 ActionCodeSettings 对象。在这种情况下,必须使用 ActionCodeSettings 对象来指定在用户点击链接后,要让用户返回到何处以完成登录。执行该操作将生成电子邮件操作链接。

与密码重设和电子邮件验证不同,这里使用的电子邮件地址不必属于现有用户,因为此操作可用于通过电子邮件链接让新用户登录您的应用。

Node.js

// Admin SDK API to generate the sign in with email link.
const useremail = 'user@example.com';
getAuth()
  .generateSignInWithEmailLink(useremail, actionCodeSettings)
  .then((link) => {
    // Construct sign-in with email link template, embed the link and
    // send using custom SMTP server.
    return sendSignInEmail(useremail, displayName, link);
  })
  .catch((error) => {
    // Some error occurred.
  });

Java

String email = "user@example.com";
try {
  String link = FirebaseAuth.getInstance().generateSignInWithEmailLink(
      email, actionCodeSettings);
  // Construct email verification template, embed the link and send
  // using custom SMTP server.
  sendCustomEmail(email, displayName, link);
} catch (FirebaseAuthException e) {
  System.out.println("Error generating email link: " + e.getMessage());
}

Python

email = 'user@example.com'
link = auth.generate_sign_in_with_email_link(email, action_code_settings)
# Construct email from a template embedding the link, and send
# using a custom SMTP server.
send_custom_email(email, link)

Go

email := "user@example.com"
link, err := client.EmailSignInLink(ctx, email, actionCodeSettings)
if err != nil {
	log.Fatalf("error generating email link: %v\n", err)
}

// Construct sign-in with email link template, embed the link and send
// using custom SMTP server.
sendCustomEmail(email, displayName, link)

C#

var email = "user@example.com";
var link = await FirebaseAuth.DefaultInstance.GenerateSignInWithEmailLinkAsync(
    email, actionCodeSettings);
// Construct email verification template, embed the link and send
// using custom SMTP server.
SendCustomEmail(email, displayName, link);

生成链接后,可以将其插入自定义登录电子邮件,然后使用自定义 SMTP 服务器通过电子邮件发送给相应的用户。

如需了解详情,请参阅通过电子邮件链接对用户进行 Firebase 身份验证。这将有助于提供有关如何在用户点击链接并重定向回应用后完成登录的信息。