2025-05-07 14:57:50 +00:00
2022-08-07 11:38:07 +02:00
2020-06-18 21:04:52 +00:00
2018-09-29 23:57:25 +02:00
2020-06-18 21:04:52 +00:00
2025-05-07 14:57:50 +00:00
2024-04-14 17:55:42 +02:00

@push.rocks/smartmail

A unified format for representing and dealing with emails

Install

To install @push.rocks/smartmail, you'll need Node.js installed on your system. With Node.js installed, run the following command in your terminal:

pnpm add @push.rocks/smartmail

This will add @push.rocks/smartmail to your project's dependencies.

Features

  • Advanced Email Address Validation: Validate email format, check for disposable/free domains, and verify MX records
  • Rich Email Representation: Create emails with multiple recipients, attachments, HTML content, and custom headers
  • Template Support: Use mustache templates for dynamic content in subject, body, and HTML
  • MIME Formatting: Convert emails to standard MIME format for sending
  • Caching & Performance: Smart caching of DNS lookups for better performance

Usage

@push.rocks/smartmail provides a unified format for representing and dealing with emails in a Node.js environment. Below, you will find several examples showcasing how to use its main features.

Importing the Module

First, ensure you're using ESM (ECMAScript Modules) syntax in your TypeScript project. Then, import the necessary classes:

import {
  Smartmail,
  EmailAddressValidator
} from '@push.rocks/smartmail';

Email Address Validation

Basic Email Validation

// Create validator with default options
const emailValidator = new EmailAddressValidator();

// Validate an email address
const result = await emailValidator.validate('user@example.com');
console.log(result);
/*
{
  valid: true,           // Overall validity
  formatValid: true,     // Email format is valid
  localPartValid: true,  // Local part (before @) is valid
  domainPartValid: true, // Domain part (after @) is valid
  mxValid: true,         // Domain has valid MX records
  disposable: false,     // Not a disposable email domain
  freemail: false,       // Not a free email provider
  reason: 'Email is valid'
}
*/

Advanced Validation Options

// Create validator with custom options
const validator = new EmailAddressValidator({
  skipOnlineDomainFetch: true,  // Use only local domain list
  cacheDnsResults: true,        // Cache DNS lookups
  cacheExpiryMs: 7200000        // Cache expires after 2 hours
});

// Validate each part of an email separately
const isValidFormat = validator.isValidEmailFormat('user@example.com');
const isValidLocalPart = validator.isValidLocalPart('user');
const isValidDomain = validator.isValidDomainPart('example.com');

// Check for disposable or free email providers
const result = await validator.validate('user@gmail.com');
if (result.freemail) {
  console.log('This is a free email provider');
}

Creating and Using Smartmail Objects

Basic Email Creation

// Create a simple email
const email = new Smartmail({
  from: 'sender@example.com',
  to: ['recipient@example.com'],
  subject: 'Hello from SmartMail',
  body: 'This is a plain text email'
});

Using Creation Object Reference

The Smartmail constructor accepts a generic type parameter that lets you associate any additional data with your email, accessible later via the getCreationObject() method. This is useful for tracking, referencing original data sources, or maintaining context:

// Define your custom reference type
interface OrderNotification {
  orderId: string;
  customerName: string;
  items: string[];
  total: number;
}

// Create email with typed creation object reference
const orderEmail = new Smartmail<OrderNotification>({
  from: 'orders@example.com',
  to: ['customer@example.com'],
  subject: 'Your Order #{{orderId}} Confirmation',
  body: 'Thank you for your order, {{customerName}}!',
  // Store the full order data as reference
  creationObjectRef: {
    orderId: '12345',
    customerName: 'John Smith',
    items: ['Product A', 'Product B'],
    total: 99.95
  }
});

// Later, retrieve the original reference data
const orderData = orderEmail.getCreationObject();
console.log(`Processing email for order ${orderData.orderId}`);
console.log(`Order total: $${orderData.total}`);

// Use the reference data for templating
const subject = orderEmail.getSubject(orderData);  // "Your Order #12345 Confirmation"
const body = orderEmail.getBody(orderData);        // "Thank you for your order, John Smith!"

This powerful feature allows you to:

  • Maintain a link to original data sources
  • Pass the email object between systems while preserving context
  • Avoid duplicating data between email content and your application
  • Use the reference data to fill template variables
  • Access metadata about the email that doesn't get included in the actual message

Adding Recipients

const email = new Smartmail({
  from: 'sender@example.com',
  subject: 'Meeting Invitation',
  body: 'Please join our meeting'
});

// Add recipients in various ways
email.addRecipient('primary@example.com');
email.addRecipients(['user1@example.com', 'user2@example.com']);
email.addRecipient('manager@example.com', 'cc');
email.addRecipients(['observer1@example.com', 'observer2@example.com'], 'bcc');

Template Variables in Subject and Body

const template = new Smartmail({
  from: 'notifications@example.com',
  subject: 'Welcome, {{name}}!',
  body: 'Hello {{name}},\n\nWelcome to our service. Your account ({{email}}) has been activated.',
  htmlBody: '<h1>Welcome, {{name}}!</h1><p>Hello {{name}},<br><br>Welcome to our service. Your account (<strong>{{email}}</strong>) has been activated.</p>'
});

// Apply template variables
const subject = template.getSubject({ name: 'John Doe' });
const plainBody = template.getBody({ name: 'John Doe', email: 'john@example.com' });
const htmlBody = template.getHtmlBody({ name: 'John Doe', email: 'john@example.com' });

Adding Attachments

import { Smartfile } from '@push.rocks/smartfile';

const email = new Smartmail({
  from: 'sender@example.com',
  to: ['recipient@example.com'],
  subject: 'Report Attached',
  body: 'Please find the attached report.'
});

// Add file attachments
const report = new Smartfile.fromLocalPath('/path/to/report.pdf');
const image = new Smartfile.fromLocalPath('/path/to/image.png');
email.addAttachment(report);
email.addAttachment(image);

Setting Email Importance and Headers

const email = new Smartmail({
  from: 'sender@example.com',
  to: ['recipient@example.com'],
  subject: 'Urgent: System Alert',
  body: 'Critical system alert requires immediate attention.'
});

// Set high priority
email.setPriority('high');

// Add custom headers
email.addHeader('X-Custom-ID', '12345');
email.addHeader('X-System-Alert', 'Critical');

Converting to MIME Format for Sending

const email = new Smartmail({
  from: 'sender@example.com',
  to: ['recipient@example.com'],
  subject: 'Hello {{name}}',
  body: 'Text version: Hello {{name}}',
  htmlBody: '<p>HTML version: Hello <strong>{{name}}</strong></p>',
  validateEmails: true // Will validate all emails before converting
});

// Convert to MIME format with template data
const mimeObj = await email.toMimeFormat({ name: 'John' });

// Result can be used with nodemailer or other email sending libraries
console.log(mimeObj);
/*
{
  from: 'sender@example.com',
  to: ['recipient@example.com'],
  subject: 'Hello John',
  text: 'Text version: Hello John',
  html: '<p>HTML version: Hello <strong>John</strong></p>',
  attachments: [...],
  headers: {...}
}
*/

API Reference

EmailAddressValidator

Constructor Options

  • skipOnlineDomainFetch: Boolean (default: false) - Skip fetching domain list from online source
  • cacheDnsResults: Boolean (default: true) - Cache DNS lookup results
  • cacheExpiryMs: Number (default: 3600000) - Cache expiry in milliseconds

Methods

  • validate(email: string): Validates email address completeness
  • isValidEmailFormat(email: string): Checks if email format is valid
  • isValidLocalPart(localPart: string): Validates local part of email
  • isValidDomainPart(domainPart: string): Validates domain part of email
  • checkMxRecords(domain: string): Checks MX records for a domain

Smartmail

Constructor Options

  • from: Email address of sender
  • to, cc, bcc: Optional arrays of recipient email addresses
  • subject: Email subject line
  • body: Plain text email body
  • htmlBody: Optional HTML version of email body
  • replyTo: Optional reply-to email address
  • headers: Optional key-value pairs of custom headers
  • priority: 'high' | 'normal' | 'low' (default: 'normal')
  • validateEmails: Boolean (default: false) - Validate all emails
  • creationObjectRef: Optional reference data of any type (generic T) - Store arbitrary data with the email

Methods

  • addRecipient(email, type?): Add a single recipient (to/cc/bcc)
  • addRecipients(emails, type?): Add multiple recipients
  • setReplyTo(email): Set reply-to address
  • setPriority(priority): Set email priority
  • addHeader(name, value): Add custom header
  • getSubject(data?): Get processed subject with template variables
  • getBody(data?): Get processed plain text body
  • getHtmlBody(data?): Get processed HTML body
  • validateAllEmails(): Validate all email addresses
  • toMimeFormat(data?): Convert to MIME format object
  • getCreationObject(): Get the stored reference data of type T

This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the license file within this repository.

Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.

Company Information

Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany

For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

Description
A unified format for representing and dealing with emails, with support for attachments and email validation.
Readme 629 KiB
Languages
TypeScript 100%