Emails

Sending emails

Learn how to send emails in TurboStarter.

The strategy for sending emails, that every provider has to implement, is extremely simple:

export interface EmailProviderStrategy {
  send: (args: {
    to: string;
    subject: string;
    text: string;
    html?: string;
  }) => Promise<void>;
}

You don't need to worry much about it, as all the providers are already configured for you. Just be aware of it if you want to add your custom provider.

Then, we define a general sendEmail function that you can use as an API for sending emails in your app:

const sendEmail = async <T extends EmailTemplate>({
  to,
  template,
  variables,
}: {
  to: string;
  template: T;
  variables: EmailVariables[T];
}) => {
  const strategy = strategies[provider];
  const { html, text, subject } = await getTemplate({
    id: template,
    variables,
  });
 
  return strategy.send({ to, subject, html, text });
};

The arguments are:

  • to: The recipient's email address.
  • template: The email template to use.
  • variables: The variables to pass to the template.

It returns a promise that resolves when the email is sent successfully. If there is an error, the promise will be rejected with an error message.

To send an email, just invoke the sendEmail with the correct arguments from the server-side of your application:

import { sendEmail } from "@turbostarter/email/server";
 
sendEmail({
  to: "user@example.com",
  template: EmailTemplate.WELCOME,
  variables: {
    name: "John Doe",
  },
});

And that's it! You're ready to send emails in your application 🚀

Last updated on

On this page

No Headings
Ship your startup everywhere. In minutes.Get TurboStarter