DEV Community

femtowork Inc.
femtowork Inc.

Posted on

How to Send i18n HTML Emails from Scripts Using React Email

Introduction

React Email is a convenient tool that allows you to design HTML emails using React components. It supports styling with Tailwind and can automatically convert to Plain Text for email clients that don't support HTML emails, making it easier to manage emails. There are a few configurations required when sending emails using React Email from a script(such batch script), and I will share the idea here.

Challenges

  • TypeScript constraints
    Since we need to handle React components, errors occur in .ts files.

    • i18n settings If the email content is multilingual, i18n-related settings are required.

Solutions

  • Change the script extension to .tsx

With the tsx command, it is possible to execute .tsx files.

npm exec tsx ./scripts/send-mail.tsx
Enter fullscreen mode Exit fullscreen mode
  • i18n settings Set up i18next and react-i18next, then wrap the React component with I18nextProvider to render it.

Example Code

// scripts/send-mail.tsx
import path, { join } from 'path'
import { fileURLToPath } from 'url'
import i18next from 'i18next'
import Backend from 'i18next-fs-backend'
import { I18nextProvider } from 'react-i18next'
import { renderAsync } from '@react-email/components'
import EmailComponent from './EmailComponent'

const lang = 'en'
const namespaces = ['common', 'mail']
const __dirname = path.dirname(fileURLToPath(import.meta.url)) // current directory

await i18next.use(Backend).init({
ns: namespaces,
lng: lang,
backend: {
loadPath: join(__dirname, '../public/locales/{{lng}}/{{ns}}.json'), // locale file path
},
})

const t = i18next.t // usable as the t function

const { html, text } = await renderReactEmail(
<I18nextProvider i18n={i18next}>
<EmailComponent />
</I18nextProvider>
)

// Send mail using html and text

async function renderReactEmail(react: ReactElement) {
const [html, text] = await Promise.all([
renderAsync(react),
renderAsync(react, { plainText: true }),
])
return { html, text }
}

Enter fullscreen mode Exit fullscreen mode

Conclusion

We introduced a method for sending multilingual React emails from a script.

Top comments (1)

Collapse
 
clementjanssens profile image
Clément Janssens

Or you can use Mailhub.sh
There is a built-in feature to manage i18n 🙂