256 lines
8.8 KiB
Markdown
256 lines
8.8 KiB
Markdown
# @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:
|
|
|
|
```bash
|
|
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:
|
|
|
|
```typescript
|
|
import {
|
|
Smartmail,
|
|
EmailAddressValidator
|
|
} from '@push.rocks/smartmail';
|
|
```
|
|
|
|
## Email Address Validation
|
|
|
|
### Basic Email Validation
|
|
|
|
```typescript
|
|
// 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
|
|
|
|
```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
|
|
});
|
|
|
|
// 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
|
|
|
|
```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'
|
|
});
|
|
```
|
|
|
|
### Adding Recipients
|
|
|
|
```typescript
|
|
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
|
|
|
|
```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' });
|
|
```
|
|
|
|
### 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);
|
|
```
|
|
|
|
### Setting Email Importance and Headers
|
|
|
|
```typescript
|
|
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
|
|
|
|
```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
|
|
});
|
|
|
|
// 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
|
|
|
|
#### 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
|
|
|
|
## 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.
|
|
|
|
### 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.
|