Emails

Learn how to send emails with React Email and Resend.

Important

This feature is only included for the following templates:

Cloudflare Monorepo
Vercel Monorepo

Setup

These instructions assume that you already have a domain on Cloudflare or a similar DNS provider. We recommend using Cloudflare if you want to make use of Cloudflare Email Routing to send and receive emails from your Gmail inbox without having to pay for a GSuite account.

  1. Create a new account on Resend.
  2. Navigate to Domains and add a new domain. This domain should either be the same as your app's domain or a subdomain of it.
    • Resend recommends using a subdomain instead of the root domain so that you can segment your emails by purpose (e.g. transactional vs marketing).
  3. Update your DNS records, and go through all of the DNS verification steps (see Resend's documentation for more details).
  4. Navigate to API Keys and create a new API key. This key will be used to authenticate your requests to Resend's API. You can leave all other settings as default.
  5. Add the API key to your .env file:
    /apps/web/.env
    RESEND_API_KEY="{{re_resend_api_key}}"

Sending emails

Within any of the API routes, the Resend client is available on the Hono context (i.e. c.var.resend). Use this to send emails from your server.

apps/web/src/server/router/example/router.ts
import { MyEmailTemplate } from "@workspace/emails";
import { appConfig } from "@/appConfig";
import { getFactory } from "@/server/router/factory";
import { isAuthenticated } from "@/server/router/middleware"

export const exampleRouter = getFactory()
    .createApp()
    .post("/", isAuthenticated({ id: "example" }), async (c) => {
        /* ... */
        const { resend, user } = c.var;

        await resend.emails
            .send({
                from: appConfig.email.noReplyMailTo,
                to: user.email,
                subject: "This is a test email",
                react: await MyEmailTemplate({
                    name: user.name,
                    message: "This is a test email sent from Hono!",
                }),
            })

        return c.json({ ok: true }, 200);
    });

Creating email templates

The MyEmailTemplate is a React component that you can create in the template's emails package. This is located in /packages/emails.

packages/emails/templates/MyEmailTemplate.tsx
import { Body, Head, Html, Row, Text } from "@react-email/components";
import type { EmailComponent } from "../../types";
import { Card, CardContent } from "../../components/Card";
import { TailwindProvider } from "../../components/TailwindProvider";

export interface MyEmailTemplateProps {
    name: string;
    message: string;
}

export const MyEmailTemplate: EmailComponent<MyEmailTemplateProps> = ({
    name,
    message,
}) => {
    return (
        <Html>
            <Head />
            <TailwindProvider>
                <Body className="bg-background font-sans text-base py-8">
                    <Card className="my-8 max-w-lg">
                        <CardContent>
                            <Row>
                                <Text>Hello {name}!</Text>
                                <Text>{message}</Text>
                            </Row>
                        </CardContent>
                    </Card>
                </Body>
            </TailwindProvider>
        </Html>
    );
};

Once you have created your email templates, make sure to build the package so that the templates are compiled and ready to be used. You can do this by running:

/packages/emails
pnpm run build

You can preview your email templates in the /emails package by running the following command:

/packages/emails
pnpm run email:studio

Avoiding the spam folder

To reduce the chances of your emails being marked as spam, there are several best-practices you can follow:

  1. Use a verified domain: Make sure to use a domain that you own and have verified with Resend.
  2. Set up SPF, DKIM, and DMARC records: These records help email providers verify that your emails are legitimate and not spoofed. Resend provides detailed instructions on how to set these up in their documentation.
  3. Add an unsubscribe link: If you're sending marketing emails, make sure to include an unsubscribe link in your emails. This is not only a best practice but also a legal requirement in many jurisdictions.
  4. Avoid spammy content: Be mindful of the content of your emails. Avoid using excessive capitalization, exclamation marks, and spammy keywords that might trigger spam filters (e.g. "free", "guaranteed", "urgent", etc.).
  5. Avoid links to suspicious domains: Make sure that the links in your emails point to legitimate and trusted domains. Avoid using URL shorteners or links that redirect to unknown sites.

Email routing to/from Gmail

Important

The following documentation assumes you've already set up your domain within Cloudflare. If your domain is managed on another provider (e.g. Vercel), you will need to transfer your domain to Cloudflare before proceeding.

If you only care to send and receive emails from your domain, and don't want to pay for a GSuite account, you can use Cloudflare Email Routing and Gmail's SMTP server to achieve this.

Receiving emails from your domain

If you want to receive emails from your domain to a Gmail inbox, you can set up Cloudflare Email Routing.

To set up email routing, follow these steps:

  1. Navigate to your domain on the Cloudflare dashboard.
    • You can find your domains within the "Account Home" page.
    • Click on the domain you want to set up email routing for.
  2. On the domains page, click on the "Email" link in the left sidebar.
  3. Go to the Destination addresses tab and add a new destination address.
    • This should be your Gmail address that you wish to route emails to. cloudflare email routing
  4. Go to the Routing rules tab and click on the Create address button.
    • Enter the email address you want to route emails from
    • Specify the destination address you added in the previous step.
    • Click on the Save button to create the routing rule. Note that this may take a few minutes to propagate, so be patient.
  5. Send a a test email to the address you set up in the previous step.
    • You should receive the email in your Gmail inbox.
    • If you don't receive the email, your email routing may not have fully propagated yet. Wait a few more minutes and try again later.
    • If you still don't receive the test email, try changing the email address that you are using to send the test email. The email routing may not work if it detects that the email being sent will be to the same address that it is routing to.

Sending emails from your domain

Cloudflare Email Routing allows you to receive emails from your domain, but it does not allow you to send emails from your domain. To send emails from your domain, you can use Gmail's SMTP server.

This answer from the Cloudflare community outlines the steps you need to follow to set this up.

Re-posting the steps here for convenience:

  1. Make sure you have 2FA enabled on your Gmail account.
  2. In your same Google Account, create an App Password.
    • If you need to select an app and device, select "Mail" as the app, and your computer as the device.
    • Copy the generated password, as you will need it later.
  3. In your Gmail account, go to "Settings" -> "Accounts and Import" tab -> "Send mail as" section.
    • The "Settings" can be found by clicking on the gear icon in the top right corner of Gmail. If you see the "Quick settings" menu, click on "See all settings" to access the full settings page.
  4. Click on "Add another email address" and fill in the first form with your name and the email address you want to send emails from (i.e. the email address you set-up in step 4 of the previous section within Cloudflare Email Routing).
    • Make sure to uncheck the "Treat as an alias" checkbox.
  5. Fill in the second form with the following details:
    • SMTP Server: smtp.gmail.com
    • Port: 587
    • Username: your Gmail address (the destination address you specified in step 3 of the previous section)
    • Password: the App Password you generated in step 2
    • Check the "Secured connection using TLS" option
    • Click on "Add Account" to finish the setup
  6. You will receive a verification email from Gmail, asking you to confirm that you own the email with a code. Copy the code and paste it into the dialog (or click on the link in the email to verify your email address).

Now you can send emails from your domain using your Gmail account. When you compose a new email, you will see the email address you added in the "From" dropdown menu. You can select it to send emails from that address.