產生電子郵件動作連結

行動應用程式有時需要與使用者互動,並透過傳送電子郵件,提示使用者採取特定動作。

Firebase 用戶端 SDK 的作用是向使用者傳送電子郵件,其中包含用於重設密碼、電子郵件地址驗證和電子郵件登入的連結。這些範本式電子郵件是由 Google 傳送,且可自訂的項目有限。

如要改用自己的電子郵件範本和自己的電子郵件傳送服務,本頁面將說明如何使用 Firebase Admin SDK,透過程式輔助方式產生上述流程的動作連結,您可以在要傳送給使用者的電子郵件中加入這些流程。

它具有以下優點:

  • 自訂電子郵件範本。包括新增樣式和自訂品牌宣傳功能、變更用詞和標誌、使用名字而非全名來聯絡使用者等等。
  • 根據內容套用不同的範本。舉例來說,如果使用者要驗證電子郵件才能訂閱電子報,則可能需要在電子郵件內容中提供背景資訊。另一個例子是電子郵件連結登入:在一個情境中,同一個使用者或其他使用者的邀請可能會觸發這個事件。需要在電子郵件中加入背景資訊。
  • 將自訂電子郵件範本本地化。
  • 可從安全的伺服器環境產生連結。
  • 可自訂透過行動應用程式或瀏覽器開啟連結的方式,以及如何傳遞其他狀態資訊等。
  • 建立電子郵件動作連結時,可以自訂用於行動應用程式流程的動態連結網域,甚至可以根據情境或行動應用程式指定不同的動態連結網域。

初始化 ActionCodeSettings

您可能需要初始化 ActionCodeSettings 例項,才能產生電子郵件動作連結。

ActionCodeSettings 可讓您透過繼續網址傳遞其他狀態,也就是在使用者點選電子郵件連結後可存取的繼續網址。此外,完成操作後,使用者也能返回應用程式。此外,您可以指定是否要在安裝後,直接從行動應用程式處理電子郵件動作連結,或是從瀏覽器加以處理。

對於要使用行動應用程式開啟的連結,您需要啟用 Firebase 動態連結並執行一些任務,從行動應用程式偵測這些連結。請參閱有關如何設定 Firebase 動態連結的電子郵件動作的操作說明。

如要初始化 ActionCodeSettings 例項,請提供下列資料:

參數 類型 說明
url 字串

設定在不同情況下具有不同意義的連結 (狀態/繼續網址):

  • 在網頁動作小工具中處理連結時,這就是 continueUrl 查詢參數中的深層連結。
  • 如果是直接在應用程式中處理連結,這是 Dynamic Link 深層連結中的 continueUrl 查詢參數。
iOS ({bundleId: string}|未定義) 設定軟體包 ID。如果已安裝 Apple 應用程式,系統將嘗試開啟連結。您必須在 Play 管理中心註冊應用程式。
android ({packageName: string, installApp:boolean|undefined, minVersion: string|undefined}|undefined) 設定 Android 套件名稱。如果已安裝,系統會嘗試在 Android 應用程式中開啟連結。如果傳遞 installApp,則會指定在裝置支援且尚未安裝應用程式的情況下,安裝 Android 應用程式。如果提供這個欄位時沒有 packageName,系統會擲回錯誤,說明 packageName 必須和這個欄位一併提供。如果已指定 minimumVersion,且已安裝舊版應用程式,系統會將使用者導向 Play 商店,以便升級應用程式。您必須在控制台中註冊該 Android 應用程式。
handleCodeInApp (布林值|未定義) 指定先在行動應用程式或網頁連結中開啟電子郵件動作連結。預設值為 false。設為 true 時,動作代碼連結會以通用連結或 Android 應用程式連結的形式傳送,安裝完成後會由應用程式開啟。如果是錯誤情況,程式碼會先傳送至網頁小工具,安裝完成後繼續重新導向至應用程式。
dynamicLinkDomain (字串|未定義) 設定目前連結要使用 Firebase Dynamic Links 開啟的動態連結網域 (或子網域)。由於每項專案可以設定多個動態連結網域,這個欄位可讓您明確選擇一個網域。如未提供,則會預設使用最舊的網域。

以下範例說明如何傳送以 Firebase 動態連結的形式,先在行動應用程式中開啟的電子郵件驗證連結 (Apple 應用程式 com.example.ios 或 Android 應用程式 com.example.android;如果尚未安裝,則應用程式會安裝,且最低版本為 12)。深層連結將包含繼續網址酬載 https://www.example.com/checkout?cartId=1234。使用的動態連結網域為 coolapp.page.link,必須設為與 Firebase 動態連結搭配使用。

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 驗證使用者。這有助於提供資訊,瞭解如何在使用者點選連結並重新導向回應用程式後,完成登入程序。