diff --git a/docs/docs-platform.yml b/docs/docs-platform.yml index 663ad7ab3..5afdbc846 100644 --- a/docs/docs-platform.yml +++ b/docs/docs-platform.yml @@ -110,6 +110,9 @@ pages: - path: concepts/backend-integration.mdx platforms: ["next", "react", "js", "python"] + + - path: concepts/emails.mdx + platforms: ["next", "react", "js"] # No Python (server-side email functionality) # Components (React-like only) - path: components/overview.mdx @@ -227,6 +230,9 @@ pages: - path: sdk/types/user.mdx platforms: ["next", "react", "js"] # No Python + + - path: sdk/types/email.mdx + platforms: ["next", "react", "js"] # No Python # SDK Hooks (React-like only) - path: sdk/hooks/use-stack-app.mdx diff --git a/docs/templates/concepts/emails.mdx b/docs/templates/concepts/emails.mdx new file mode 100644 index 000000000..592db9114 --- /dev/null +++ b/docs/templates/concepts/emails.mdx @@ -0,0 +1,197 @@ +--- +title: Email System +description: Send custom emails to your users with Stack Auth's email system. +--- + +Stack Auth provides an email system that allows you to send custom emails to your users. The system supports both custom HTML emails and template-based emails with theming. + +## Overview + +The email system provides: + +- **Email Sending**: Send custom emails to users via the `sendEmail` method on `StackServerApp` +- **Email Templates**: Use predefined email templates for common authentication flows +- **Email Themes**: Apply consistent styling to your emails +- **Notification Categories**: Allow users to control which emails they receive + +## Server-Side Email Sending + +### Basic Email Sending + +Use the `sendEmail` method on your server app to send emails to users: + +```typescript +import { stackServerApp } from './stack'; + +// Send a custom HTML email +const result = await stackServerApp.sendEmail({ + userIds: ['user-id-1', 'user-id-2'], + subject: 'Welcome to our platform!', + html: '

Welcome!

Thanks for joining us.

', +}); + +if (result.status === 'error') { + console.error('Failed to send email:', result.error); +} +``` + +### Template-Based Emails + +Send emails using predefined templates with variables: + +```typescript +// Send email using a template +const result = await stackServerApp.sendEmail({ + userIds: ['user-id'], + templateId: 'welcome-template', + subject: 'Welcome to our platform!', + variables: { + userName: 'John Doe', + activationUrl: 'https://yourapp.com/activate/token123', + supportEmail: 'support@yourapp.com', + }, +}); +``` + +### Email Options + +The `sendEmail` method accepts the following options: + +```typescript +type SendEmailOptions = { + userIds: string[]; // Array of user IDs to send to + themeId?: string | null | false; // Theme to apply (optional) + subject?: string; // Email subject + notificationCategoryName?: string; // Notification category for user preferences +} & ( + | { + html: string; // Custom HTML content + } + | { + templateId: string; // Template ID to use + variables?: Record; // Template variables + } +); +``` + +### Error Handling + +The `sendEmail` method returns a `Result` type that can contain specific errors: + +```typescript +const result = await stackServerApp.sendEmail({ + userIds: ['user-id'], + html: '

Hello!

', + subject: 'Test Email', +}); + +if (result.status === 'error') { + switch (result.error.code) { + case 'REQUIRES_CUSTOM_EMAIL_SERVER': + console.error('Please configure a custom email server'); + break; + case 'SCHEMA_ERROR': + console.error('Invalid email data provided'); + break; + case 'USER_ID_DOES_NOT_EXIST': + console.error('One or more user IDs do not exist'); + break; + } +} +``` + + + +## Built-in Email Templates + +Stack Auth provides several built-in email templates for common authentication flows: + +- **Email Verification**: `email_verification` - Sent when users need to verify their email +- **Password Reset**: `password_reset` - Sent when users request password reset +- **Magic Link**: `magic_link` - Sent for passwordless authentication +- **Team Invitation**: `team_invitation` - Sent when users are invited to teams +- **Sign-in Invitation**: `sign_in_invitation` - Sent to invite users to sign up + +These templates can be customized through the admin interface or programmatically. + +## Email Configuration + +### Shared Email Provider (Development) + +For development, you can use Stack's shared email provider: + +```typescript +// In your project configuration +{ + emailConfig: { + type: 'shared', // Uses Stack's shared email service + } +} +``` + +### Custom Email Server (Production) + +For production, configure your own email server: + +```typescript +// In your project configuration +{ + emailConfig: { + type: 'standard', + host: 'smtp.yourprovider.com', + port: 587, + username: 'your-username', + password: 'your-password', + senderEmail: 'noreply@yourdomain.com', + senderName: 'Your App Name', + } +} +``` + +## Notification Categories + +Control which emails users receive by organizing them into notification categories: + +```typescript +await stackServerApp.sendEmail({ + userIds: ['user-id'], + html: '

New feature available!

', + subject: 'Product Updates', + notificationCategoryName: 'product_updates', +}); +``` + +Users can then opt in or out of specific notification categories through their account settings. + +## Best Practices + +1. **Use Templates**: Leverage built-in templates for consistent branding and easier maintenance +2. **Handle Errors**: Always check the result status and handle potential errors +3. **Respect User Preferences**: Use notification categories to let users control what emails they receive +4. **Server-Side Only**: Always send emails from your server-side code, never from the client + +## React Components Integration + +The email system integrates seamlessly with Stack Auth's React components. Email verification, password reset, and other authentication emails are automatically sent when users interact with the provided components. + +For custom email flows, use the `sendEmail` method from your server-side code: + +```typescript +// In your API route or server action +import { stackServerApp } from './stack'; + +export async function inviteUser(email: string) { + const result = await stackServerApp.sendEmail({ + userIds: [userId], // Get user ID first + templateId: 'invitation-template', + subject: 'You\'re invited!', + variables: { + inviteUrl: 'https://yourapp.com/invite/token123', + }, + }); + + return result; +} +``` + +This email system gives you control over your application's email communications while maintaining the security and reliability of Stack Auth's infrastructure. diff --git a/docs/templates/meta.json b/docs/templates/meta.json index ac1bf07a0..a8f5a5178 100644 --- a/docs/templates/meta.json +++ b/docs/templates/meta.json @@ -14,6 +14,7 @@ "concepts/api-keys", "concepts/backend-integration", "concepts/custom-user-data", + "concepts/emails", "concepts/oauth", "concepts/auth-providers", "concepts/orgs-and-teams", diff --git a/docs/templates/sdk/index.mdx b/docs/templates/sdk/index.mdx index 3b5b6e7ac..c76d1afe7 100644 --- a/docs/templates/sdk/index.mdx +++ b/docs/templates/sdk/index.mdx @@ -40,6 +40,12 @@ export const sdkSections = [ { name: "ServerTeamProfile", href: "types/team-profile#serverteamprofile", icon: "type" }, ] }, + { + title: "Email", + items: [ + { name: "SendEmailOptions", href: "types/email#sendemaildoptions", icon: "type" }, + ] + }, { title: "Hooks", items: [ diff --git a/docs/templates/sdk/meta.json b/docs/templates/sdk/meta.json index 391e9852e..0e64521f0 100644 --- a/docs/templates/sdk/meta.json +++ b/docs/templates/sdk/meta.json @@ -14,6 +14,7 @@ "types/team-permission", "types/team-profile", "types/contact-channel", + "types/email", "types/api-key", "types/project", "types/connected-account", diff --git a/docs/templates/sdk/objects/stack-app.mdx b/docs/templates/sdk/objects/stack-app.mdx index 874287658..8389ff1d3 100644 --- a/docs/templates/sdk/objects/stack-app.mdx +++ b/docs/templates/sdk/objects/stack-app.mdx @@ -525,6 +525,7 @@ exposing [`SECRET_SERVER_KEY`](../../rest-api/overview.mdx) on the client. // NEXT_LINE_PLATFORM react-like ⤷ useUsers([options]): ServerUser[]; //$stack-link-to:#stackserverappuseusersoptions createUser([options]): Promise; //$stack-link-to:#stackserverappcreateuseroptions + sendEmail(options): Promise>; //$stack-link-to:#stackserverappsendemailoptions getTeam(id): Promise; //$stack-link-to:#stackserverappgetteamid // NEXT_LINE_PLATFORM react-like @@ -799,6 +800,77 @@ const user = await stackServerApp.createUser({ + + + + + + Send custom emails to users. You can send either custom HTML emails or use predefined templates with variables. + + **Parameters:** + - `options` ([SendEmailOptions](../types/email#sendemaildoptions)) - Email configuration and content + + **Returns:** `Promise>` + + The method returns a `Result` object that can contain specific error types: + + - `RequiresCustomEmailServer` - No custom email server configured + - `SchemaError` - Invalid email data provided + - `UserIdDoesNotExist` - One or more user IDs don't exist + + + + + + +```typescript +declare function sendEmail(options: SendEmailOptions): Promise>; +``` + + + + + + Send HTML Email + Send Template Email + + +```typescript +const result = await stackServerApp.sendEmail({ + userIds: ['user-1', 'user-2'], + subject: 'Welcome to our platform!', + html: '

Welcome!

Thanks for joining us.

', +}); + +if (result.status === 'error') { + console.error('Failed to send email:', result.error); +} +``` +
+ +```typescript +const result = await stackServerApp.sendEmail({ + userIds: ['user-1'], + templateId: 'welcome-template', + variables: { + userName: 'John Doe', + activationUrl: 'https://app.com/activate/token123', + }, +}); + +if (result.status === 'error') { + console.error('Failed to send email:', result.error); +} +``` + +
+ +
+ +
+
+
+ ## Team Management diff --git a/docs/templates/sdk/types/email.mdx b/docs/templates/sdk/types/email.mdx new file mode 100644 index 000000000..0c39579c6 --- /dev/null +++ b/docs/templates/sdk/types/email.mdx @@ -0,0 +1,206 @@ +--- +title: Email +full: true +--- + +This is a detailed reference for email-related types in Stack Auth. If you're looking for a more high-level overview, please refer to our [guide on the email system](../../concepts/emails.mdx). + +On this page: +- [SendEmailOptions](#sendemaildoptions) + +--- + +# `SendEmailOptions` + +Options for sending emails via the `sendEmail` method on `StackServerApp`. + +### Table of Contents + +; //$stack-link-to:#sendemaildoptionsvariables + } +);`} /> + + + + + An array of user IDs that will receive the email. All users must exist in your Stack Auth project. + + + + ```typescript + userIds: string[] + ``` + + + ```typescript + { + userIds: ['user-1', 'user-2', 'user-3'], + // ... other options + } + ``` + + + + + + + + + Optional theme ID to apply to the email. Use `null` for no theme, `false` to use the default theme, or a string ID for a specific theme. + + + + ```typescript + themeId?: string | null | false + ``` + + + ```typescript + { + themeId: 'corporate-theme-id', + // or + themeId: null, // no theme + // or + themeId: false, // default theme + // ... other options + } + ``` + + + + + + + + + Optional email subject line. If using a template, this overrides the template's default subject. + + + + ```typescript + subject?: string + ``` + + + ```typescript + { + subject: 'Welcome to our platform!', + // ... other options + } + ``` + + + + + + + + + Optional notification category name for user preferences. Users can opt in or out of specific categories through their account settings. + + + + ```typescript + notificationCategoryName?: string + ``` + + + ```typescript + { + notificationCategoryName: 'product_updates', + // ... other options + } + ``` + + + + + + + + + Custom HTML content for the email. Use this option when you want to send a custom HTML email instead of using a template. + + + + ```typescript + html: string + ``` + + + ```typescript + { + userIds: ['user-1'], + html: '

Welcome!

Thanks for joining us.

', + subject: 'Welcome to our platform' + } + ``` +
+
+
+
+ + + + + ID of the email template to use. Use this option when you want to send a template-based email with variables. + + + + ```typescript + templateId: string + ``` + + + ```typescript + { + userIds: ['user-1'], + templateId: 'welcome-template', + variables: { + userName: 'John Doe', + activationUrl: 'https://app.com/activate/token123' + } + } + ``` + + + + + + + + + Optional variables to substitute in the template. Only used when `templateId` is provided. + + + + ```typescript + variables?: Record + ``` + + + ```typescript + { + templateId: 'welcome-template', + variables: { + userName: 'John Doe', + activationUrl: 'https://app.com/activate/token123', + supportEmail: 'support@yourapp.com' + } + } + ``` + + + +