產生電子郵件動作連結

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

Firebase 用戶端 SDK 可讓您傳送電子郵件給使用者,內含可用於重設密碼、驗證電子郵件地址及以電子郵件登入的連結。這些電子郵件是 Google 根據範本傳送,自訂程度有限。

如果您想改用自己的電子郵件範本和電子郵件傳送服務,請參閱本頁說明,瞭解如何使用 Firebase Admin SDK,以程式輔助方式產生上述流程的動作連結,並將這些連結加入傳送給使用者的電子郵件。

這項機制有以下好處:

  • 自訂電子郵件範本。包括新增樣式和自訂品牌、變更措辭和標誌、以名字而非全名稱呼使用者等。
  • 視情況套用不同範本。舉例來說,如果使用者要驗證電子郵件地址來訂閱電子報,可能需要在電子郵件內容中提供相關背景資訊。另一個例子是透過電子郵件連結登入:在某個情境中,這可能是由同一位使用者觸發,或是由其他使用者發出邀請。電子郵件中必須包含相關背景資訊。
  • 將自訂電子郵件範本翻譯成當地語言。
  • 能夠從安全的伺服器環境產生連結。
  • 可自訂連結的開啟方式 (透過行動應用程式或瀏覽器),以及如何傳遞額外狀態資訊等。
  • 建構電子郵件動作連結時,可自訂用於行動應用程式流程的行動連結網域。

初始化 ActionCodeSettings

您可能需要先初始化 ActionCodeSettings 執行個體,才能產生電子郵件動作連結。

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

如要透過行動應用程式開啟連結,您需要執行一些工作,從行動應用程式偵測這些連結。如需電子郵件動作的行動連結設定說明,請參閱這篇文章

如要初始化 ActionCodeSettings 執行個體,請提供下列資料:

參數 類型 說明
url 字串

設定連結 (狀態/繼續網址),在不同情境中具有不同意義:

  • 在網頁動作小工具中處理連結時,這是 continueUrl 查詢參數中的深層連結。
  • 如果應用程式直接處理連結,這就是連結深層連結中的 continueUrl 查詢參數。Hosting
iOS ({bundleId: string}|undefined) 設定 iOS 軟體包 ID,協助Firebase Authentication判斷是否應建立僅限網頁或行動裝置的連結,並在 Apple 裝置上開啟
android ({packageName: string, installApp:boolean|undefined, minimumVersion: string|undefined}|undefined) 設定 Android 套件名稱,協助 Firebase Authentication 判斷是否應建立僅限網頁的連結或行動連結,並在 Android 裝置上開啟
handleCodeInApp (boolean|undefined) 電子郵件動作連結會先在行動應用程式或網頁連結中開啟。預設值為 false。如果設為 true,系統會將動作代碼連結做為通用連結或 Android 應用程式連結傳送,並在安裝應用程式後開啟。如果為 false,系統會先將驗證碼傳送至網頁小工具,然後在使用者繼續操作時,將其重新導向至應用程式 (如果已安裝)。
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',
  },
  // The domain must be configured in Firebase Hosting and owned by the project.
  linkDomain: 'custom-domain.com',
};

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