@vikeriait/nuxt-transport-mailer
v1.2.1
Published
Robust Nuxt module for sending emails with Nodemailer, featuring built-in API, Zod validation, Captcha protection, and Rate Limiting.
Downloads
547
Readme
Nuxt Transport Mailer
A robust and flexible Nuxt module for sending emails using Nodemailer. It offers a ready-to-use server API endpoint, TypeScript support, Zod validation, and built-in security features like Captcha and Rate Limiting.
Features
- 📧 Transport Support: Easily configure SMTP or AWS SES transports.
- 🌐 Edge Ready: Built-in support for Edge environments (Cloudflare Workers, etc.) using
aws4fetchfor AWS SES. - 🚀 Server-Side API: Optional built-in API endpoint (
/api/mail/send) to send emails from your frontend. - 🛡️ Security First:
- Integrated Captcha support (Cloudflare Turnstile, Google reCAPTCHA, hCaptcha).
- Rate Limiting support (via
nuxt-securityintegration). - Honeypot field protection.
- ✅ Validation: Strict email body validation using Zod.
- 🛠️ Composable:
useMailer()composable for easy client-side integration. - ⚙️ Type Safe: Full TypeScript support with auto-completion.
Quick Setup
- Add
@vikeriait/nuxt-transport-mailerdependency to your project:
# Using pnpm
pnpm add @vikeriait/nuxt-transport-mailer
# Using npm
npm install @vikeriait/nuxt-transport-mailer
# Using yarn
yarn add @vikeriait/nuxt-transport-mailer- Add
@vikeriait/nuxt-transport-mailerto themodulessection ofnuxt.config.ts:
export default defineNuxtConfig({
modules: [
'@vikeriait/nuxt-transport-mailer'
],
transportMailer: {
// Module configuration
}
})Configuration
Configure the module in your nuxt.config.ts under the transportMailer key.
export default defineNuxtConfig({
modules: ['@vikeriait/nuxt-transport-mailer'],
transportMailer: {
// Select the driver ('smtp' or 'ses')
driver: 'smtp',
// SMTP Configuration (Standard Nodemailer options)
smtp: {
host: 'smtp.example.com',
port: 587,
secure: false,
auth: {
user: '',
pass: '',
},
},
// OR AWS SES Configuration
ses: {
endpoint: undefined, // Optional: Custom endpoint (useful for testing or localstack)
clientConfig: {
// For Edge (aws4fetch): Credentials must be explicit
// For Node (AWS SDK): Optional if using standard AWS_ env vars
region: 'eu-central-1',
credentials: {
accessKeyId: '',
secretAccessKey: '',
}
},
commandConfig: {},
},
// Default options for all emails
defaults: {
from: '"My Application" <[email protected]>',
},
// Server API Endpoint Configuration
serverApi: {
enabled: true, // Enable the /api/mail/send endpoint
route: '/api/mail/send', // Customize the route path
},
// Security Configuration
security: {
// Captcha Configuration (Custom module feature)
captcha: {
enabled: true,
provider: 'turnstile', // 'turnstile' | 'recaptcha' | 'hcaptcha'
secretKey: '',
},
// Nuxt Security Route Rules (Integrates with nuxt-security)
// You can add any valid nuxt-security route rule here (CORS, Rate Limiting, etc.)
rateLimiter: {
tokensPerInterval: 5,
interval: 300000, // 5 minutes
},
corsHandler: {
origin: '*',
methods: ['POST']
}
},
},
})Environment Variables
You can also configure the module using environment variables.
[!NOTE] Node.js / Standard Usage: The AWS SDK automatically detects standard environment variables (
AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_REGION). You don't need to explicitly map them innuxt.config.ts.Edge / aws4fetch: The
aws4fetchclient requires explicit configuration. You must either map your environment variables innuxt.config.tsor use the specific Nuxt-namespaced variables below.
# SMTP
NUXT_TRANSPORT_MAILER_SMTP_HOST=smtp.example.com
NUXT_TRANSPORT_MAILER_SMTP_PORT=587
NUXT_TRANSPORT_MAILER_SMTP_AUTH_USER=myuser
NUXT_TRANSPORT_MAILER_SMTP_AUTH_PASS=mypassword
NUXT_TRANSPORT_MAILER_SMTP_SECURE=false
# AWS SES (Node.js - Auto-detected)
AWS_REGION=...
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...
# AWS SES (Edge - Explicit mapping required)
# OR Map these in nuxt.config.ts to process.env.AWS_*
NUXT_TRANSPORT_MAILER_SES_CLIENT_CONFIG_REGION=...
NUXT_TRANSPORT_MAILER_SES_CLIENT_CONFIG_ACCESS_KEY_ID=...
NUXT_TRANSPORT_MAILER_SES_CLIENT_CONFIG_SECRET_ACCESS_KEY=...
# Optional custom endpoint
NUXT_TRANSPORT_MAILER_SES_ENDPOINT=...
NUXT_TRANSPORT_MAILER_SECURITY_CAPTCHA_ENABLED=true
NUXT_TRANSPORT_MAILER_SECURITY_CAPTCHA_PROVIDER=turnstile
NUXT_TRANSPORT_MAILER_SECURITY_CAPTCHA_SECRET_KEY=XXXXXXXXXXXXXXXXXXXXXXXXX
NUXT_TRANSPORT_MAILER_DEFAULTS_FROM='"My Application" <[email protected]>'Usage
Client-Side (Using useMailer)
The module provides a useMailer composable to send emails easily from your Vue components.
<script setup lang="ts">
const { send, pending, error, data } = useMailer()
const turnstileToken = ref('')
async function submitForm() {
await send({
to: '[email protected]',
subject: 'New Inquiry',
text: 'Hello, I would like to know more about your services.',
html: '<p>Hello, I would like to know more about your services.</p>',
// If captcha is enabled, pass the token
captchaToken: turnstileToken.value
})
if (!error.value) {
alert('Email sent successfully!')
}
}
</script>Server-Side
You can send emails directly from your server-side API handlers or middleware using sendMail.
// server/api/custom-email.post.ts
import { sendMail } from '#imports'
export default defineEventHandler(async (event) => {
try {
const result = await sendMail({
to: '[email protected]',
subject: 'Welcome!',
text: 'Thank you for signing up.',
})
return { success: true, result }
} catch (error) {
// Handle error
throw createError({ statusCode: 500, message: 'Failed to send email' })
}
})Security & Validation
[!IMPORTANT] To use the integrated security features (Rate Limiting, CORS, etc.), you must have nuxt-security installed and enabled in your project.
Captcha
To enable Captcha, configure the security.captcha options. When enabled, you must include a captchaToken field in the request body containing the token received from your captcha provider. The module validates this token server-side before processing the email. You must provide a valid secretKey for your chosen provider.
Honeypot
The built-in API endpoint includes a honeypot protection. You can add a hidden field named _gotcha to your form. If this field is filled (which bots usually do), the request will be accepted but the email will not be sent, silently preventing spam.
Rate Limiting
This module integrates with nuxt-security (if installed) to apply rate limiting to the mailer endpoint. You can configure tokensPerInterval and interval in the config.
Validation
The email body is validated using Zod. The following fields are supported:
to,cc,bcc(at least one is required)subjecttext,htmlfrom,replyTo_gotcha(honeypot field)captchaToken(required if captcha is enabled)
Development
# Install dependencies
pnpm install
# Prepare
pnpm dev:prepare
# Run playground
pnpm dev
# Run tests
pnpm test