BREAKING CHANGE(smartmail): Improve email validation and Smartmail features: add detailed validation for email parts, caching for MX lookups, multi-recipient support, custom headers, and update dependency imports and build scripts.
This commit is contained in:
237
readme.md
237
readme.md
@@ -1,19 +1,27 @@
|
||||
# @push.rocks/smartmail
|
||||
a unified format for representing and dealing with mails
|
||||
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
|
||||
npm install @push.rocks/smartmail --save
|
||||
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, including email address validation and creation of mail objects with attachments.
|
||||
`@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
|
||||
|
||||
@@ -26,81 +34,206 @@ import {
|
||||
} from '@push.rocks/smartmail';
|
||||
```
|
||||
|
||||
### Validate Email Addresses
|
||||
## Email Address Validation
|
||||
|
||||
You can validate email addresses to check whether they are disposable, belong to a free email provider, or verify their validity in terms of having an MX record.
|
||||
### Basic Email Validation
|
||||
|
||||
```typescript
|
||||
// Instantiate the EmailAddressValidator
|
||||
// Create validator with default options
|
||||
const emailValidator = new EmailAddressValidator();
|
||||
|
||||
// Validate an email address
|
||||
const validateEmail = async (email: string) => {
|
||||
const validationResult = await emailValidator.validate(email);
|
||||
console.log(validationResult);
|
||||
};
|
||||
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'
|
||||
}
|
||||
*/
|
||||
```
|
||||
|
||||
// Example usage
|
||||
validateEmail('example@gmail.com').then(() => {
|
||||
console.log('Email validation completed.');
|
||||
### 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'
|
||||
});
|
||||
```
|
||||
|
||||
### Creating and Using Smartmail Objects
|
||||
|
||||
`Smartmail` class allows you to represent an email in a structured way, including attachments, subject, body, and more. Here's how to use it:
|
||||
### 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 { Smartmail } from '@push.rocks/smartmail';
|
||||
import { Smartfile } from '@push.rocks/smartfile';
|
||||
|
||||
// Create a new Smartmail object
|
||||
const myMail = new Smartmail({
|
||||
from: 'no-reply@yourdomain.com',
|
||||
subject: 'Welcome to Our Service',
|
||||
body: 'Hello {{name}}, welcome to our service!'
|
||||
const email = new Smartmail({
|
||||
from: 'sender@example.com',
|
||||
to: ['recipient@example.com'],
|
||||
subject: 'Report Attached',
|
||||
body: 'Please find the attached report.'
|
||||
});
|
||||
|
||||
// Use Smartfile to prepare an attachment (optional)
|
||||
const attachment = new Smartfile.fromLocalPath('path/to/your/attachment.pdf');
|
||||
myMail.addAttachment(attachment);
|
||||
|
||||
// Accessing and modifying the mail object's properties
|
||||
console.log(myMail.getSubject({ name: 'John Doe' }));
|
||||
console.log(myMail.getBody({ name: 'John Doe' }));
|
||||
|
||||
// The `getCreationObject` method can be used to retrieve the original creation object
|
||||
console.log(myMail.getCreationObject());
|
||||
// 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);
|
||||
```
|
||||
|
||||
### Email Address Validation Details
|
||||
|
||||
The `EmailAddressValidator` class fetches domain information either from a local JSON file or an online source to categorize email domains as disposable, free, or valid based on MX records. Here's a deeper look into validating email addresses and interpreting the results:
|
||||
### Setting Email Importance and Headers
|
||||
|
||||
```typescript
|
||||
// Instantiate the validator
|
||||
const validator = new EmailAddressValidator();
|
||||
|
||||
// Validate an email
|
||||
validator.validate('someone@disposablemail.com').then(result => {
|
||||
if (result.valid && !result.disposable) {
|
||||
console.log('Email is valid and not disposable.');
|
||||
} else {
|
||||
console.log('Email is either invalid or disposable.');
|
||||
}
|
||||
if (result.freemail) {
|
||||
console.log('Email belongs to a free mail provider.');
|
||||
}
|
||||
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');
|
||||
```
|
||||
|
||||
### Handling Attachments
|
||||
### Converting to MIME Format for Sending
|
||||
|
||||
As shown in the example, attachments can be added to a `Smartmail` object. `Smartfile` (from `@push.rocks/smartfile`) is utilized to handle file operations, allowing you to attach files easily to your email object. Ensure that attachments are in the appropriate format and accessible before adding them to the `Smartmail` object.
|
||||
```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
|
||||
});
|
||||
|
||||
### Conclusion
|
||||
// Convert to MIME format with template data
|
||||
const mimeObj = await email.toMimeFormat({ name: 'John' });
|
||||
|
||||
These examples cover the basics of using `@push.rocks/smartmail` for handling emails within your Node.js applications. By leveraging the `Smartmail` and `EmailAddressValidator` classes, you can efficiently represent, validate, and manage email data, enhancing the robustness and functionality of your email-related features.
|
||||
// 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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user