2024-02-15 20:30:38 +01:00
2024-02-15 20:30:38 +01:00
2025-05-08 12:46:10 +00:00
2024-02-15 20:30:38 +01:00
2025-05-07 20:20:17 +00:00
2024-02-15 20:30:38 +01:00
2024-02-15 20:30:38 +01:00
2024-02-15 20:30:38 +01:00
2024-02-15 20:30:38 +01:00
2025-05-07 20:20:17 +00:00
2025-05-08 12:46:10 +00:00
2025-05-08 12:46:10 +00:00

@serve.zone/platformservice

contains the platformservice container with mail, sms, letter, ai services.

Install

To install @serve.zone/platformservice, run the following command:

npm install @serve.zone/platformservice --save

Make sure you have Node.js and npm installed on your system to use this package.

Usage

This document provides extensive usage scenarios for the @serve.zone/platformservice, a comprehensive ESM module written in TypeScript offering a wide range of services such as mail, SMS, letter, and artificial intelligence (AI) functionalities. This service is an exemplar of a modular design, allowing users to leverage various communication methods and AI services efficiently. Key features provided by this platform include sending and receiving emails, managing SMS services, letter dispatching, and utilizing AI for diverse purposes.

Prerequisites

Before diving into the examples, ensure you have the platform service installed and configured correctly. The package leverages environment variables for configuration, so you must set up the necessary variables, including service endpoints, authentication tokens, and database connections.

Initialization

First, initialize the platform service, ensuring all dependencies are correctly loaded and configured:

import { SzPlatformService } from '@serve.zone/platformservice';

async function initService() {
  const platformService = new SzPlatformService();
  await platformService.start();
  console.log('Platform service initialized successfully.');
}

initService();

Sending Emails

One of the primary services offered is email management. Here's how to send an email using the platform service:

import { EmailService, IEmailOptions } from '@serve.zone/platformservice';

async function sendEmail() {
  const emailOptions: IEmailOptions = {
    from: 'no-reply@example.com',
    to: 'recipient@example.com',
    subject: 'Test Email',
    body: '<h1>This is a test email</h1>',
  };

  const emailService = new EmailService(platformService);
  await emailService.sendEmail(emailOptions);
  
  console.log('Email sent successfully.');
}

sendEmail();

Managing SMS

Similar to email, the platform also facilitates SMS sending:

import { SmsService, ISmsConstructorOptions } from '@serve.zone/platformservice';

async function sendSms() {
  const smsOptions: ISmsConstructorOptions = {
    apiGatewayApiToken: 'SMS_API_TOKEN', // Replace with your real token
  };

  const smsService = new SmsService(smsOptions);
  await smsService.sendSms(1234567890, 'SENDER_NAME', 'This is a test SMS.');
  
  console.log('SMS sent successfully.');
}

sendSms();

Dispatching Letters

For physical mail correspondence, the platform provides a letter service:

import { LetterService, ILetterConstructorOptions } from '@serve.zone/platformservice';

async function sendLetter() {
  const letterOptions: ILetterConstructorOptions = {
    letterxpressUser: 'USER',
    letterxpressToken: 'TOKEN',
  };

  const letterService = new LetterService(letterOptions);
  await letterService.sendLetter('This is a test letter body.', {address: 'Recipient Address', name: 'Recipient Name'});
  
  console.log('Letter dispatched successfully.');
}

sendLetter();

Mail Transfer Agent (MTA) and Consolidated Email Handling

The platform includes a robust Mail Transfer Agent (MTA) for enterprise-grade email handling with complete control over the email delivery process. Additionally, the platform now features a consolidated email configuration system with pattern-based routing and a streamlined directory structure:

graph TD
    API[API Clients] --> ApiManager
    SMTP[External SMTP Servers] <--> UnifiedEmailServer
    
    subgraph "DcRouter Email System"
        DcRouter[DcRouter] --> UnifiedEmailServer[Unified Email Server]
        DcRouter --> DomainRouter[Domain Router]
        UnifiedEmailServer --> MultiModeProcessor[Multi-Mode Processor]
        MultiModeProcessor --> ForwardMode[Forward Mode]
        MultiModeProcessor --> MtaMode[MTA Mode]
        MultiModeProcessor --> ProcessMode[Process Mode]
        ApiManager[API Manager] --> DcRouter
    end
    
    subgraph "Mail System Structure"
        MailCore[mail/core] --> EmailClasses[Email, TemplateManager, etc.]
        MailDelivery[mail/delivery] --> MtaService[MTA Service]
        MailDelivery --> EmailSendJob[Email Send Job]
        MailRouting[mail/routing] --> DnsManager[DNS Manager]
        MailSecurity[mail/security] --> AuthClasses[DKIM, SPF, DMARC]
        MailServices[mail/services] --> ServiceClasses[EmailService, ApiManager]
    end
    
    subgraph "External Services"
        DnsManager <--> DNS[DNS Servers]
        EmailSendJob <--> MXServers[MX Servers]
        ForwardMode <--> ExternalSMTP[External SMTP Servers]
    end

Key Features

The email handling system provides:

  • Modular Directory Structure: Clean organization with clear separation of concerns:
    • mail/core: Core email models and basic functionality (Email, BounceManager, etc.)
    • mail/delivery: Email delivery mechanisms (MTA, SMTP server, rate limiting)
    • mail/routing: DNS and domain routing capabilities
    • mail/security: Authentication and security features (DKIM, SPF, DMARC)
    • mail/services: High-level services and API interfaces
  • Pattern-based Routing: Route emails based on glob patterns like *@domain.com or *@*.domain.com
  • Multi-Modal Processing: Handle different email domains with different processing modes:
    • Forward Mode: SMTP forwarding to other servers
    • MTA Mode: Full Mail Transfer Agent capabilities
    • Process Mode: Store-and-forward with content scanning
  • Unified Configuration: Single configuration interface for all email handling
  • Shared Infrastructure: Use same ports (25, 587, 465) for all email handling
  • Complete SMTP Server: Receive emails with TLS and authentication support
  • DKIM, SPF, DMARC: Full email authentication standard support
  • Content Scanning: Check for spam, viruses, and other threats
  • Advanced Delivery Management: Queue, retry, and track delivery status

Using the Consolidated Email System

Here's how to use the consolidated email system:

import { DcRouter, IEmailConfig, EmailProcessingMode } from '@serve.zone/platformservice';

async function setupEmailHandling() {
  // Configure the email handling system
  const dcRouter = new DcRouter({
    emailConfig: {
      ports: [25, 587, 465],
      hostname: 'mail.example.com',
      
      // TLS configuration
      tls: {
        certPath: '/path/to/cert.pem',
        keyPath: '/path/to/key.pem'
      },
      
      // Default handling for unmatched domains
      defaultMode: 'forward' as EmailProcessingMode,
      defaultServer: 'fallback.mail.example.com',
      defaultPort: 25,
      
      // Pattern-based routing rules
      domainRules: [
        {
          // Forward all company.com emails to internal mail server
          pattern: '*@company.com',
          mode: 'forward' as EmailProcessingMode,
          target: {
            server: 'internal-mail.company.local',
            port: 25,
            useTls: true
          }
        },
        {
          // Process notifications.company.com with MTA
          pattern: '*@notifications.company.com',
          mode: 'mta' as EmailProcessingMode,
          mtaOptions: {
            domain: 'notifications.company.com',
            dkimSign: true,
            dkimOptions: {
              domainName: 'notifications.company.com',
              keySelector: 'mail',
              privateKey: '...'
            }
          }
        },
        {
          // Scan marketing emails for content and transform
          pattern: '*@marketing.company.com',
          mode: 'process' as EmailProcessingMode,
          contentScanning: true,
          scanners: [
            {
              type: 'spam',
              threshold: 5.0,
              action: 'tag'
            }
          ],
          transformations: [
            {
              type: 'addHeader',
              header: 'X-Marketing',
              value: 'true'
            }
          ]
        }
      ]
    }
  });
  
  // Start the system
  await dcRouter.start();
  console.log('DcRouter with email handling started');
  
  // Later, you can update rules dynamically
  await dcRouter.updateDomainRules([
    {
      pattern: '*@newdomain.com',
      mode: 'forward' as EmailProcessingMode,
      target: {
        server: 'mail.newdomain.com',
        port: 25
      }
    }
  ]);
}

setupEmailHandling();

Using the MTA Service Directly

You can still use the MTA service directly for more granular control with our new modular directory structure:

import { SzPlatformService } from '@serve.zone/platformservice';
import { MtaService } from '@serve.zone/platformservice/mail/delivery';
import { Email } from '@serve.zone/platformservice/mail/core';
import { ApiManager } from '@serve.zone/platformservice/mail/services';

async function useMtaService() {
  // Initialize platform service
  const platformService = new SzPlatformService();
  await platformService.start();
  
  // Initialize MTA service
  const mtaService = new MtaService(platformService);
  await mtaService.start();
  
  // Send an email
  const email = new Email({
    from: 'sender@yourdomain.com',
    to: 'recipient@example.com',
    subject: 'Hello World',
    text: 'This is a test email',
    html: '<p>This is a <b>test</b> email</p>',
    attachments: [] // Optional attachments
  });
  
  const emailId = await mtaService.send(email);
  console.log(`Email queued with ID: ${emailId}`);
  
  // Check email status
  const status = mtaService.getEmailStatus(emailId);
  console.log(`Email status: ${status.status}`);
  
  // Set up API for external access
  const apiManager = new ApiManager(platformService.emailService);
  await apiManager.start(3000);
  console.log('MTA API running on port 3000');
}

useMtaService();

The consolidated email system provides key advantages for applications requiring:

  • Domain-specific email handling
  • Flexible email routing
  • High-volume email sending
  • Compliance with email authentication standards
  • Detailed delivery tracking
  • Custom email handling logic
  • Multi-domain email management
  • Complete control over email infrastructure

Leveraging AI Services

The platform also integrates AI functionalities, allowing for innovative use cases like generating content, analyzing text, or automating responses:

import { AiService } from '@serve.zone/platformservice';

async function useAiService() {
  const aiService = new AiService('OPENAI_API_KEY'); // Replace with your real API key
  const response = await aiService.generateText('Prompt for the AI service.');

  console.log(`AI response: ${response}`);
}

useAiService();
Description
enabling commonly needed services like mail sending, letter sending, phone calling, ai functions for clusters.
Readme 2.4 MiB
Languages
TypeScript 99.8%
Dockerfile 0.2%