AI Personalization

AI Intelligence Engine

NexoMailer integrates with state-of-the-art LLMs (OpenAI, OpenRouter, Anthropic) to transform your email infrastructure from a delivery tool into an intelligent marketing assistant.

Installation

Install the AI module via your preferred package manager. It is recommended to use npm for maximum compatibility:

npm install @nexomailer/ai

(Alternatively, you can use pnpm add @nexomailer/ai or yarn add @nexomailer/ai).


Features at a Glance

  • Personalizer: Rewrite templates for specific recipients.
  • Spam Analyst: Predict and fix spam triggers before sending.
  • Subject Optimizer: A/B test subject lines with AI-predicted scores.
  • Brand Consistency: Automatically maintains your company's tone and style.

1. Advanced Configuration

NexoMailer supports any provider via OpenRouter, allowing you to use models like Claude 3.5 or Llama 3. Here is how you initialize the core SDK with the AI module configured.

import { NexoMailer } from '@nexomailer/core';
 
// Initialize the mailer with the AI configuration
const mailer = new NexoMailer({
  // AI Module specific settings
  ai: {
    // You can use 'openai' or 'openrouter' to access multiple models
    provider: 'openrouter', 
    
    // Your LLM API Key (ALWAYS load from environment variables)
    apiKey: process.env.AI_API_KEY,
    
    // Choose the exact model you want to run your prompts against
    model: 'anthropic/claude-3.5-sonnet', 
    
    // Temperature controls creativity. 0.7 gives a good balance of creativity and accuracy.
    temperature: 0.7,
    
    // Maximum tokens the AI is allowed to return in a single response
    maxTokens: 2000
  },
  
  // Global branding settings that the AI will automatically follow
  branding: {
    companyName: 'NexoDev',
    tone: 'Professional but creative' // AI respects this tone in every output!
  }
});
 
// Always initialize to verify connections
await mailer.init();

2. Specialized AI Tools

Subject Optimizer

Generate high-converting subject lines with predicted open rate scores.

// Call the AI optimizer utility directly
const result = await mailer.ai.optimizeSubject({
  // Your original, basic subject line
  subject: 'Check out our new features',
  
  // The target demographic you want to optimize for
  audience: 'SaaS Founders',
  
  // Number of variations you want the AI to generate
  variations: 3
});
 
// The result is an array of optimized subjects, complete with an AI-predicted score.
console.log(result);
// Returns: 
// [
//   { subject: '🚀 New Features to Scale Your SaaS', score: 95, reasoning: 'Strong action verb...' },
//   ...
// ]

Spam Shield

Analyze your email content for spam filters before you hit send.

// Pass the raw subject and HTML to the Spam Shield analyzer
const analysis = await mailer.ai.spamCheck({
  subject: 'WIN FREE MONEY NOW!!!',
  html: '<h1>Limited time offer click here</h1>'
});
 
// The AI gives you a clear verdict (e.g., "safe", "likely_spam")
console.log(analysis.verdict); // "likely_spam"
 
// It also provides a list of actionable improvements to bypass filters
console.log(analysis.improvements); 
// ["Remove all-caps from subject", "Avoid urgency triggers like 'NOW!!!'"]

3. 1-on-1 Personalization

Inject dynamic, relevant content into your templates based on recipient data.

// AI Personalizer takes a base template and recipient context
const personalized = await mailer.ai.personalize({
  // The name of the template or raw HTML you want to personalize
  template: 'welcome',
  
  // Data specific to the user receiving this exact email
  recipient: {
    name: 'Ankit',
    industry: 'DevOps',
    recentActivity: 'Starred our repo'
  },
  
  // The specific tone/style you want for this individual message
  style: 'Casual and welcoming'
});
 
// Now send the email using the personalized subject and HTML generated by the AI
await mailer.send({
  to: 'ankit@example.com',
  subject: personalized.subject, // Automatically generated
  html: personalized.html          // Automatically injected with context
});

🚀 Real-World Use Cases

1. Re-activating Dormant Users

Instead of a generic "We miss you" email, use AI to reference their last activity and offer a personalized incentive.

const result = await mailer.ai.generate({
  // The instruction for the AI
  prompt: 'Write a re-engagement email for a user who hasn\'t logged in for 30 days.',
  // Provide the context variables
  context: {
    lastProject: 'Mobile App Design',
    daysInactive: 30
  },
  tone: 'warm'
});

2. Multi-Language Outreach

Scale your business globally by automatically localizing your emails while keeping the core message intact.

const localized = await mailer.ai.personalize({
  html: welcomeMjml, // Your base english template
  // The AI detects the language requirement automatically from the context
  recipient: { country: 'Japan', language: 'Japanese' },
  style: 'Polite and formal'
});

3. Smart Newsletter Summaries

If you send long-form content, use AI to generate a "TL;DR" (Too Long; Didn't Read) section at the top of your email to increase engagement.

const summary = await mailer.ai.generate({
  // Ask the AI to condense the text
  prompt: `Summarize this article into 3 bullet points: ${articleText}`,
  length: 'short'
});

4. Dynamic Product Pitches

Change how you describe a feature based on whether the recipient is a Developer, a Marketer, or a CEO.

const pitch = await mailer.ai.personalize({
  html: featureAnnouncementHtml,
  // Tell the AI who is reading it
  recipient: { role: 'CEO' },
  // Give it a strict objective
  style: 'Focus on ROI and business growth'
});

Performance & Token Management

[!TIP] Cost Optimization: AI operations are expensive. We recommend using personalize only for high-value leads or spamCheck once during template design.

[!IMPORTANT] Error Handling: NexoMailer includes built-in AIRateLimitError. Always catch this to handle provider downtime or token limits gracefully.