Send
Send a predefined email using the API route
Send emails using Nuxt and the MailChannels Node.js SDK.
Add the mailchannels-sdk package dependency to your Nuxt project.
npm i mailchannels-sdkyarn add mailchannels-sdkpnpm add mailchannels-sdkbun add mailchannels-sdkdeno add npm:mailchannels-sdkAdd your MailChannels API key to your .env file.
NUXT_MAILCHANNELS_API_KEY=your-api-keyThen, add the mailchannels object and apiKey property to the runtimeConfig in your nuxt.config.ts. The value of apiKey should be an empty string, which will be automatically set at runtime using the value of process.env.NUXT_MAILCHANNELS_API_KEY.
export default defineNuxtConfig({
runtimeConfig: {
mailchannels: {
apiKey: '' // This should be an empty string here
}
}
})Register a Server handler under server/api/send.post.ts.
Use the html property to send an email with HTML content.
import { MailChannels } from 'mailchannels-sdk'
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig(event)
const mailchannels = new MailChannels(config.mailchannels.apiKey)
const { data, error } = await mailchannels.emails.send({
from: 'Name <from@example.com>',
to: 'to@example.com',
subject: 'Test email',
html: '<p>Hello World</p>'
})
if (error) {
throw createError({
status: error.statusCode || 400,
message: error.message
})
}
return data
})