LogoBoring Template

Email Service

Send emails using Resend and React Email components in your application.

This template uses Resend for email services. For more information, visit the Resend documentation.

Setup

Prerequisites

Resend Account

📧 Active Resend.com account

Verified Domain

✅ Domain or email verified in Resend

React Email

⚛️ Components for email templates

Installation

Install the required packages:

Terminal
npm install resend @react-email/components

Environment Variables

Add the following variables to your .env.local file:

.env.local
# Resend Configuration
RESEND_API_KEY=your_resend_api_key
RESEND_EMAIL=your_verified_email

Make sure to verify your domain or email address in Resend before using it as a sender.

Implementation

Resend Client Setup

Configure the Resend client in lib/resend.ts:

lib/resend.ts
import { Resend } from "resend";
 
export const resend = new Resend(process.env.RESEND_API_KEY);

Email Template Component

Create type-safe email templates using React Email components:

components/emails/magic-link-email.tsx
import {
  Body,
  Container,
  Head,
  Heading,
  Html,
  Link,
  Preview,
  Section,
  Tailwind,
  Text,
} from "@react-email/components";
 
type MagicLinkMailProps = {
  email: string;
  magicLinkMail: string;
};
 
export function MagicLinkMail({ email, magicLinkMail }: MagicLinkMailProps) {
  return (
    <Html>
      <Head />
      <Preview>Magic login link</Preview>
      <Tailwind>
        <Body className="m-auto bg-white font-sans">
          <Container className="mx-auto my-[40px] p-[20px]">
            <Heading className="text-[24px] font-normal">
              <strong>🪄 Your magic link</strong>
            </Heading>
            <Text className="text-[14px] leading-[24px]">
              <Link
                href={magicLinkMail}
                className="rounded-md bg-black px-4 py-2 text-white"
              >
                👉 Click here to sign in 👈
              </Link>
            </Text>
            <Section className="rounded-md bg-[#d2d2d2] px-6 py-4">
              <Text className="text-[14px]">{magicLinkMail}</Text>
            </Section>
          </Container>
        </Body>
      </Tailwind>
    </Html>
  );
}

React Email components make it easy to create responsive, well-designed emails that work across different email clients.

Usage Examples

Sending Emails

Example of sending an email with a React Email template:

lib/email-service.ts
import { resend } from "@/lib/resend";
import { MagicLinkMail } from "@/components/emails/magic-link-email";
 
async function sendMagicLink(email: string, magicLink: string) {
  await resend.emails.send({
    from: process.env.RESEND_EMAIL!,
    to: email,
    subject: "Your Magic Link",
    react: MagicLinkMail({
      email,
      magicLinkMail: magicLink,
    }),
  });
}

Error Handling

Implement proper error handling when sending emails:

lib/email-service.ts
async function sendEmailWithRetry(options) {
  try {
    const result = await resend.emails.send(options);
 
    if (result.error) {
      console.error("Failed to send email:", result.error);
      throw new Error(result.error.message);
    }
 
    return result;
  } catch (error) {
    console.error("Email service error:", error);
    // Optional: Implement retry logic here
    throw error;
  }
}

Available Components

Layout Components

🏗️ Html, Head, Body, Container, Section, etc.

Typography

🔤 Heading, Text, Link, Preview components

Styling

🎨 Tailwind integration for consistent styling

Media

📷 Image, Hr, and other media components

Email Templates

Authentication magic link template:

Secure login link

Encrypted, time-limited link for secure authentication

Fallback text link

Plain text URL for clients that don't support buttons

User email display

Shows the recipient's email for verification

Branded design

Maintains your application's brand identity

Welcome Email

New user onboarding email:

Personalized greeting

Custom welcome message with user's name

Getting started steps

Step-by-step guide for new users

Support information

Contact details for user assistance

Social links

Connect users with your social media presence

Integration with Authentication

Here's how to integrate email sending with Better-auth for magic link authentication:

lib/auth.ts
import { betterAuth } from "better-auth";
import { magicLink } from "better-auth/plugins";
import { resend } from "@/lib/resend";
import { MagicLinkMail } from "@/components/emails/magic-link-email";
 
export const auth = betterAuth({
  // ... other config
  plugins: [
    magicLink({
      sendMagicLink: async ({ email, url }) => {
        const result = await resend.emails.send({
          from: process.env.RESEND_EMAIL!,
          to: email,
          subject: `Magic Login Link from ${appName}!`,
          react: MagicLinkMail({
            email,
            magicLinkMail: url,
          }),
        });
 
        if (result.error) {
          throw new Error(result.error.message);
        }
      },
    }),
    // ... other plugins
  ],
});

Best Practices

Implementation

  • Use TypeScript for type safety
  • Create reusable components
  • Implement proper error handling
  • Test emails in development

Design

  • Ensure mobile responsiveness
  • Use web-safe fonts
  • Include plain text fallback
  • Follow email design standards

Preview and Testing

Resend provides a development mode for testing emails without actual delivery, as well as a dashboard to view sent emails.

To preview emails during development:

// In development
if (process.env.NODE_ENV === "development") {
  console.log("Email preview:", emailContent);
}
 
// In production, send the actual email
const result = await resend.emails.send({
  from: process.env.RESEND_EMAIL!,
  to: email,
  subject: "Your Magic Link",
  react: emailContent,
});

Additional Resources