电子邮件

电子邮件是 Better Auth 的关键组成部分,所有用户都必须使用,无论其身份验证方法如何。Better Auth 默认提供电子邮件和密码身份验证,并提供许多工具帮助你管理电子邮件验证、密码重置等功能。

【Email is a key part of Better Auth, required for all users regardless of their authentication method. Better Auth provides email and password authentication out of the box, and a lot of utilities to help you manage email verification, password reset, and more.】

邮箱验证

【Email Verification】

电子邮件验证是一种安全功能,用于确保用户提供有效的电子邮件地址。通过确认电子邮件地址属于用户,它有助于防止垃圾邮件和滥用。在本指南中,你将了解如何在应用中实现基于令牌的电子邮件验证。

要使用基于一次性密码(OTP)的电子邮件验证,请查看 OTP 验证指南。

【Email verification is a security feature that ensures users provide a valid email address. It helps prevent spam and abuse by confirming that the email address belongs to the user. In this guide, you'll get a walk through of how to implement token based email verification in your app. To use otp based email verification, check out the OTP Verification guide.】

向你的应用添加电子邮件验证

【Adding Email Verification to Your App】

要启用电子邮件验证,你需要传递一个发送带有链接的验证电子邮件的函数。

【To enable email verification, you need to pass a function that sends a verification email with a link.】

  • sendVerificationEmail:当开始邮件验证时,会触发此功能。它接受一个包含以下属性的数据对象:
    • user:包含电子邮件地址的用户对象。
    • url:用户必须点击以验证其电子邮件的验证网址。
    • token:用于完成电子邮件验证的验证令牌,在实现自定义验证 URL 时使用。

并将一个 request 对象作为第二个参数。

【and a request object as the second parameter.】

auth.ts
import { betterAuth } from 'better-auth';
import { sendEmail } from './email'; // your email sending function

export const auth = betterAuth({
    emailVerification: {
        sendVerificationEmail: async ({ user, url, token }, request) => {
            void sendEmail({
                to: user.email,
                subject: 'Verify your email address',
                text: `Click the link to verify your email: ${url}`
            })
        }
    }
})

避免等待邮件发送以防止时间攻击。在无服务器平台上,使用 waitUntil 或类似方法来确保邮件已发送。

触发电子邮件验证

【Triggering Email Verification】

你可以通过多种方式发起电子邮件验证:

【You can initiate email verification in several ways:】

1. 注册时

【1. During Sign-up】

要在注册时自动发送验证电子邮件,请将 emailVerification.sendOnSignUp 设置为 true

【To automatically send a verification email at signup, set emailVerification.sendOnSignUp to true. 】

auth.ts
import { betterAuth } from 'better-auth';

export const auth = betterAuth({
    emailVerification: {
        sendOnSignUp: true
    }
})

当用户注册时,这会发送一封验证电子邮件。对于社交登录,电子邮件验证状态会从单点登录(SSO)中读取。

【This sends a verification email when a user signs up. For social logins, email verification status is read from the SSO.】

启用 sendOnSignUp 后,当用户通过未声明邮箱已验证的 SSO 登录时,Better Auth 会发送验证邮件,但即使启用了 requireEmailVerification,也不要求完成验证即可登录。

2. 需要电子邮件验证

【2. Require Email Verification】

如果你启用需要邮箱验证,用户必须先验证他们的邮箱才能登录。每次用户尝试登录时,都会调用 sendVerificationEmail

【If you enable require email verification, users must verify their email before they can log in. And every time a user tries to sign in, sendVerificationEmail is called.】

这仅在你已经实现了 sendVerificationEmailsendOnSignIn 设置为 true 且用户尝试通过电子邮件和密码登录时才有效。

auth.ts
export const auth = betterAuth({
  emailVerification: {
    sendVerificationEmail: async ({ user, url }) => {
      void sendEmail({
        to: user.email,
        subject: "Verify your email address",
        text: `Click the link to verify your email: ${url}`,
      });
    },
    sendOnSignIn: true,
  },
  emailAndPassword: {
    requireEmailVerification: true,
  },
});

如果用户在未验证其电子邮件的情况下尝试登录,你可以处理错误并向用户显示一条消息。

【If a user tries to sign in without verifying their email, you can handle the error and show a message to the user.】

auth-client.ts
await authClient.signIn.email({
    email: "email@example.com",
    password: "password"
}, {
    onError: (ctx) => {
        // Handle the error
        if(ctx.error.status === 403) {
            alert("Please verify your email address")
        }
        //you can also show the original error message
        alert(ctx.error.message)
    }
})

3. 手动

【3. Manually】

你也可以通过调用 sendVerificationEmail 手动触发电子邮件验证。

【You can also manually trigger email verification by calling sendVerificationEmail.】

await authClient.sendVerificationEmail({
    email: "user@email.com",
    callbackURL: "/" // The redirect URL after verification
})

验证电子邮件

【Verifying the Email】

如果用户点击提供的验证网址,他们的电子邮件将自动被验证,并且会被重定向到 callbackURL

【If the user clicks the provided verification URL, their email is automatically verified, and they are redirected to the callbackURL.】

对于手动验证,你可以向用户发送包含 token 的自定义链接,并调用 verifyEmail 函数。

【For manual verification, you can send the user a custom link with the token and call the verifyEmail function.】

await authClient.verifyEmail({
    query: {
        token: "" // Pass the token here
    }
})

验证后自动登录

【Auto Sign In After Verification】

要在用户成功验证他们的电子邮件后自动登录用户,请将 autoSignInAfterVerification 选项设置为 true

【To sign in the user automatically after they successfully verify their email, set the autoSignInAfterVerification option to true:】

const auth = betterAuth({
    //...your other options
    emailVerification: {
        autoSignInAfterVerification: true
    }
})

成功验证邮箱后的回调

【Callback after successful email verification】

在用户验证其电子邮件后,你可以使用 afterEmailVerification 回调立即运行自定义代码。这对于触发任何副作用非常有用,例如授予访问特殊功能的权限或记录事件。

【You can run custom code immediately after a user verifies their email using the afterEmailVerification callback. This is useful for any side-effects you want to trigger, like granting access to special features or logging the event.】

afterEmailVerification 函数会在用户的电子邮件被确认后自动运行,它会接收 user 对象和 request 详情,以便你可以针对该用户执行操作。

【The afterEmailVerification function runs automatically when a user's email is confirmed, receiving the user object and request details so you can perform actions for that specific user.】

以下是设置方法:

【Here's how you can set it up:】

auth.ts
import { betterAuth } from 'better-auth';

export const auth = betterAuth({
    emailVerification: {
        async afterEmailVerification(user, request) {
            // Your custom logic here, e.g., grant access to premium features
            console.log(`${user.email} has been successfully verified!`);
        }
    }
})

密码重置邮件

【Password Reset Email】

密码重置允许用户在忘记密码时重置密码。Better Auth 提供了一种简单的方法来实现密码重置功能。

【Password reset allows users to reset their password if they forget it. Better Auth provides a simple way to implement password reset functionality.】

你可以通过传递一个发送带有链接的密码重置电子邮件的函数来启用密码重置。

【You can enable password reset by passing a function that sends a password reset email with a link.】

auth.ts
import { betterAuth } from 'better-auth';
import { sendEmail } from './email'; // your email sending function

export const auth = betterAuth({
    emailAndPassword: {
        enabled: true,
        sendResetPassword: async ({ user, url, token }, request) => {
            void sendEmail({
                to: user.email,
                subject: 'Reset your password',
                text: `Click the link to reset your password: ${url}`
            })
        }
    }
})

避免等待邮件发送以防止时间攻击。在无服务器平台上,使用 waitUntil 或类似方法来确保邮件已发送。

查看电子邮件和密码指南,了解在应用中实现密码重置的更多详细信息。 你也可以查看 Otp 验证指南,了解如何在应用中使用 OTP 实现密码重置。

【Check out the Email and Password guide for more details on how to implement password reset in your app. Also you can check out the Otp verification guide for how to implement password reset with OTP in your app.】

On this page