Overview
The server-side useLettermint() function returns the initialized Lettermint SDK instance, giving you direct access to the full Lettermint API. This is useful when you need features beyond the simplified sendEmail utility.
Signature
function useLettermint(): Lettermint
Return Value
Returns a singleton instance of the Lettermint SDK client, configured with your API key.
Configuration
The Lettermint instance is automatically configured with:
- API Token: Read from
NUXT_LETTERMINT_API_KEY environment variable or the module configuration
- Singleton Pattern: The instance is created once and reused across all server contexts
The function will throw an error if no API key is configured:Error: Lettermint API key is not configured. Please set NUXT_LETTERMINT_API_KEY environment variable or configure it in nuxt.config.ts
Usage Examples
Fluent Email API
Multiple Recipients
With Attachments
Complex Email
// server/api/send-email.post.ts
export default defineEventHandler(async (event) => {
const lettermint = useLettermint()
const result = await lettermint.email
.from('[email protected]')
.to('[email protected]')
.subject('Welcome!')
.html('<h1>Welcome to our service!</h1>')
.tag('welcome')
.metadata({ userId: '12345' })
.send()
return result
})
// server/api/broadcast.post.ts
export default defineEventHandler(async () => {
const lettermint = useLettermint()
const result = await lettermint.email
.from('[email protected]')
.to('[email protected]')
.to('[email protected]')
.to('[email protected]')
.cc('[email protected]')
.subject('Monthly Newsletter')
.html('<p>Check out this month\'s updates!</p>')
.tag('newsletter')
.send()
return { messageId: result.message_id }
})
// server/api/send-report.post.ts
import fs from 'fs'
export default defineEventHandler(async () => {
const lettermint = useLettermint()
// Read file and convert to base64
const pdfBuffer = fs.readFileSync('./report.pdf')
const base64Content = pdfBuffer.toString('base64')
const result = await lettermint.email
.from('[email protected]')
.to('[email protected]')
.subject('Monthly Report')
.html('<p>Please find the report attached.</p>')
.attach('monthly-report.pdf', base64Content)
.send()
return { success: true, messageId: result.message_id }
})
// server/api/order-confirmation.post.ts
export default defineEventHandler(async (event) => {
const { order } = await readBody(event)
const lettermint = useLettermint()
let email = lettermint.email
.from('[email protected]')
.to(order.customerEmail)
.subject(`Order Confirmation #${order.id}`)
.html(generateOrderEmailHtml(order))
.text(generateOrderEmailText(order))
.replyTo('[email protected]')
.tag('order-confirmation')
.tag('transactional')
.metadata({
orderId: order.id,
customerId: order.customerId,
total: order.total
})
// Add BCC for record keeping
if (order.total > 1000) {
email = email.bcc('[email protected]')
}
// Add invoice attachment if available
if (order.invoicePdf) {
email = email.attach(
`invoice-${order.id}.pdf`,
order.invoicePdf
)
}
const result = await email.send()
return {
success: true,
messageId: result.message_id
}
})
Fluent Email Builder API
The Lettermint SDK uses a fluent (chainable) API for building emails:
Basic Methods
from
(email: string) => EmailBuilder
Set the sender email address.
to
(email: string) => EmailBuilder
Add a recipient. Can be called multiple times to add multiple recipients.
subject
(text: string) => EmailBuilder
text
(content: string) => EmailBuilder
Set the plain text body..text('Plain text content')
html
(content: string) => EmailBuilder
Set the HTML body..html('<h1>HTML content</h1>')
Additional Recipients
cc
(email: string) => EmailBuilder
Add a CC recipient. Can be called multiple times.
bcc
(email: string) => EmailBuilder
Add a BCC recipient. Can be called multiple times.
replyTo
(email: string) => EmailBuilder
Add a reply-to address. Can be called multiple times.
tag
(tag: string) => EmailBuilder
Add a tag for categorization. Can be called multiple times..tag('welcome')
.tag('onboarding')
metadata
(data: Record<string, string>) => EmailBuilder
Attach custom metadata for tracking..metadata({ userId: '12345', campaign: 'summer' })
Set custom email headers..headers({ 'X-Custom-Header': 'value' })
Attachments
attach
(filename: string, content: string) => EmailBuilder
Add a file attachment. Content should be a base64-encoded string..attach('document.pdf', base64String)
Sending
Send the email and return the result.const result = await email.send()
Implementation Details
The useLettermint() function:
import { Lettermint } from 'lettermint'
import { useRuntimeConfig } from '#imports'
let lettermintInstance: Lettermint | null = null
export function useLettermint(): Lettermint {
if (!lettermintInstance) {
const config = useRuntimeConfig()
if (!config.lettermint?.apiKey) {
throw new Error('Lettermint API key is not configured. Please set NUXT_LETTERMINT_API_KEY environment variable or configure it in nuxt.config.ts')
}
lettermintInstance = new Lettermint({
apiToken: config.lettermint.apiKey,
})
}
return lettermintInstance
}
Key Features:
- Singleton Pattern: Creates the instance only once and reuses it
- Lazy Initialization: Instance is created on first use
- Configuration Validation: Throws an error if API key is missing
- Runtime Config: Reads API key from Nuxt runtime configuration
When to Use
Use the direct SDK instance when you need:
- Fluent API: Prefer the chainable builder pattern
- Fine-grained control: Need access to advanced SDK features
- Dynamic email construction: Building emails conditionally with complex logic
- SDK-specific features: Features not exposed by the
sendEmail utility
Use the sendEmail utility when you:
- Want a simpler, object-based API
- Don’t need advanced SDK features
- Prefer a more straightforward function call