smartmail/readme.md

303 lines
11 KiB
Markdown
Raw Permalink Normal View History

2023-07-28 05:49:44 +02:00
# @push.rocks/smartmail
A unified format for representing and dealing with emails
2019-10-26 23:45:35 +02:00
2024-04-14 17:55:42 +02:00
## 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:
```bash
pnpm add @push.rocks/smartmail
2024-04-14 17:55:42 +02:00
```
This will add `@push.rocks/smartmail` to your project's dependencies.
2019-10-26 23:45:35 +02:00
## 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
2019-10-26 23:45:35 +02:00
## 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.
2024-04-14 17:55:42 +02:00
### Importing the Module
First, ensure you're using ESM (ECMAScript Modules) syntax in your TypeScript project. Then, import the necessary classes:
```typescript
import {
Smartmail,
EmailAddressValidator
} from '@push.rocks/smartmail';
```
## Email Address Validation
2024-04-14 17:55:42 +02:00
### Basic Email Validation
2024-04-14 17:55:42 +02:00
```typescript
// Create validator with default options
2024-04-14 17:55:42 +02:00
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
```typescript
// 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
2024-04-14 17:55:42 +02:00
});
// 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');
}
2024-04-14 17:55:42 +02:00
```
## Creating and Using Smartmail Objects
2024-04-14 17:55:42 +02:00
### Basic Email Creation
2024-04-14 17:55:42 +02:00
```typescript
// 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:
```typescript
// 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
2024-04-14 17:55:42 +02:00
```typescript
const email = new Smartmail({
from: 'sender@example.com',
subject: 'Meeting Invitation',
body: 'Please join our meeting'
2024-04-14 17:55:42 +02:00
});
// 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');
```
2024-04-14 17:55:42 +02:00
### Template Variables in Subject and Body
2024-04-14 17:55:42 +02:00
```typescript
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' });
2024-04-14 17:55:42 +02:00
```
### Adding Attachments
```typescript
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);
```
2024-04-14 17:55:42 +02:00
### Setting Email Importance and Headers
2024-04-14 17:55:42 +02:00
```typescript
const email = new Smartmail({
from: 'sender@example.com',
to: ['recipient@example.com'],
subject: 'Urgent: System Alert',
body: 'Critical system alert requires immediate attention.'
2024-04-14 17:55:42 +02:00
});
// Set high priority
email.setPriority('high');
// Add custom headers
email.addHeader('X-Custom-ID', '12345');
email.addHeader('X-System-Alert', 'Critical');
2024-04-14 17:55:42 +02:00
```
### Converting to MIME Format for Sending
2024-04-14 17:55:42 +02:00
```typescript
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
});
2024-04-14 17:55:42 +02:00
// 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: {...}
}
*/
```
2024-04-14 17:55:42 +02:00
## 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
2024-04-14 17:55:42 +02:00
## License and Legal Information
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](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.
2020-01-21 10:05:35 +00:00
2024-04-14 17:55:42 +02:00
### Company Information
2020-01-12 18:32:43 +00:00
2024-04-14 17:55:42 +02:00
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
2020-01-12 18:32:43 +00:00
2024-04-14 17:55:42 +02:00
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
2019-10-26 23:45:35 +02:00
2024-04-14 17:55:42 +02:00
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.