> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mailblock.de/llms.txt
> Use this file to discover all available pages before exploring further.

# Node JS - Getting Started

> This is our getting started to our NodeJs SDK

## Getting Started with Mailblock SDK

This guide will help you get up and running with the Mailblock SDK in just a few minutes.

## Prerequisites

* Node.js 14 or higher
* A Mailblock API key [MailBlock](https://mailblock.de)

## Installation

Install the SDK using npm:

```bash theme={null}
npm install mailblock
```

Or using yarn:

```bash theme={null}
yarn add mailblock
```

## Basic Setup

* first follow the steps from: [Basic Setup](/basic-setup)

Import and initialize the SDK with your API key:

```javascript theme={null}
import Mailblock from 'mailblock';

const client = new Mailblock('your-api-key-here');
```

## Sending Your First Email

Here's how to send a simple email:

```javascript theme={null}
const result = await client.sendEmail({
  to: 'recipient@example.com',
  from: 'sender@yourdomain.com',
  subject: 'Hello from Mailblock!',
  text: 'This is my first email using the Mailblock SDK.'
});

if (result.success) {
  console.log('Email sent successfully!');
  console.log('Email ID:', result.data.id);
} else {
  console.error('Failed to send email:', result.error);
}
```

## Using Method Chaining

The SDK also supports a fluent, chainable API:

```javascript theme={null}
const result = await client.email()
  .to('recipient@example.com')
  .from('sender@yourdomain.com')
  .subject('Hello from Mailblock!')
  .text('This email was sent using method chaining.')
  .send();
```

## Sending HTML Emails

You can send rich HTML emails instead of plain text:

```javascript theme={null}
const result = await client.sendEmail({
  to: 'recipient@example.com',
  from: 'sender@yourdomain.com',
  subject: 'Welcome to Our Service',
  html: `
    <h1>Welcome!</h1>
    <p>Thanks for signing up. We're excited to have you on board.</p>
    <a href="https://yoursite.com/dashboard">Get Started</a>
  `
});
```

## Sending to Multiple Recipients

Send emails to multiple people with CC and BCC support:

```javascript theme={null}
const result = await client.sendEmail({
  to: ['user1@example.com', 'user2@example.com'],
  cc: 'manager@example.com',
  bcc: ['audit@example.com', 'admin@example.com'],
  from: 'sender@yourdomain.com',
  subject: 'Team Update',
  text: 'This email goes to multiple recipients.'
});
```

You can also use method chaining with multiple recipients:

```javascript theme={null}
const result = await client.email()
  .to(['primary@example.com', 'secondary@example.com'])
  .cc('supervisor@example.com')
  .bcc(['audit@example.com'])
  .from('system@yourdomain.com')
  .subject('System Notification')
  .text('Multiple recipients via method chaining.')
  .send();
```

## Scheduling Emails

Schedule emails to be sent at a future date and time:

```javascript theme={null}
// Schedule email for 1 hour from now
const scheduledTime = new Date(Date.now() + 60 * 60 * 1000);

const result = await client.sendEmail({
  to: 'recipient@example.com',
  from: 'sender@yourdomain.com',
  subject: 'Scheduled Email',
  text: 'This email was scheduled to be sent later.',
  scheduledAt: scheduledTime
});

if (result.success) {
  console.log('Email scheduled successfully!');
}
```

You can also use ISO date strings:

```javascript theme={null}
const result = await client.sendEmail({
  to: 'recipient@example.com',
  from: 'sender@yourdomain.com',
  subject: 'Scheduled Email',
  text: 'This email was scheduled using an ISO string.',
  scheduledAt: '2024-12-25T09:00:00.000Z' // Christmas morning
});
```

## Managing Scheduled Emails

### Canceling Scheduled Emails

Cancel scheduled emails before they're sent:

```javascript theme={null}
// Cancel a single email
const cancelResult = await client.cancelEmail('email-id-123');

if (cancelResult.success) {
  console.log('Email cancelled successfully!');
  console.log('Previous status:', cancelResult.data.previous_status);
  console.log('Current status:', cancelResult.data.current_status);
}

// Cancel multiple emails at once
const emailIds = ['id-1', 'id-2', 'id-3'];
const bulkResult = await client.cancelEmails(emailIds);

if (bulkResult.success) {
  console.log(`Cancelled ${bulkResult.data.success_count} emails`);
  console.log(`Failed to cancel ${bulkResult.data.error_count} emails`);
}
```

### Updating Scheduled Emails

Modify scheduled emails before they're sent:

```javascript theme={null}
// Update email content
const updateResult = await client.updateScheduledEmail('email-id-123', {
  subject: 'Updated: Meeting Postponed',
  body_text: 'The meeting has been moved to next week.',
  body_html: '<p><strong>Updated:</strong> The meeting has been moved to next week.</p>'
});

// Reschedule an email
await client.updateScheduledEmail('email-id-456', {
  scheduled_at: new Date(Date.now() + 7200000) // Send in 2 hours instead
});

// Convert scheduled email to immediate send
await client.updateScheduledEmail('email-id-789', {
  scheduled_at: null, // Send immediately
  subject: 'Urgent: Sending Now!'
});
```

## Environment Configuration

For production applications, use environment variables for your API key:

```javascript theme={null}
// .env file
MAILBLOCK_API_KEY=your-api-key-here
```

```javascript theme={null}
// Your application
import Mailblock from 'mailblock';

const client = new Mailblock(process.env.MAILBLOCK_API_KEY);
```

## Debug Mode

Enable debug mode during development to see detailed logs:

```javascript theme={null}
const client = new Mailblock('your-api-key', { 
  debug: true 
});

// Now you'll see detailed logs for all API calls
const result = await client.sendEmail({
  to: 'test@example.com',
  from: 'sender@yourdomain.com',
  subject: 'Debug Test',
  text: 'Testing with debug mode enabled'
});
```

Debug logs include:

* Request details and timing
* API responses
* Error information
* Performance metrics

## TypeScript Support

The SDK includes full TypeScript support out of the box:

```typescript theme={null}
import Mailblock, { 
  EmailOptions, 
  EmailResponse, 
  CancelEmailResponse, 
  UpdateEmailOptions 
} from 'mailblock';

const client: Mailblock = new Mailblock('your-api-key');

// Send email with full type safety
const emailOptions: EmailOptions = {
  to: ['recipient@example.com', 'user2@example.com'],
  cc: 'manager@example.com',
  bcc: ['audit@example.com'],
  from: 'sender@yourdomain.com',
  subject: 'TypeScript Email',
  text: 'This email was sent with full type safety!'
};

const result: EmailResponse = await client.sendEmail(emailOptions);

// Cancel email with typed response
const cancelResult: CancelEmailResponse = await client.cancelEmail('email-id');

// Update email with typed options
const updates: UpdateEmailOptions = {
  subject: 'Updated Subject',
  body_text: 'New content',
  scheduled_at: new Date(Date.now() + 3600000)
};

await client.updateScheduledEmail('email-id', updates);
```

## Error Handling

The SDK uses a consistent response format that makes error handling straightforward:

```javascript theme={null}
const result = await client.sendEmail({
  to: 'invalid-email', // This will cause a validation error
  from: 'sender@yourdomain.com',
  subject: 'Test',
  text: 'Test message'
});

if (!result.success) {
  console.log('Error Type:', result.errorType); // 'VALIDATION_ERROR'
  console.log('Error Message:', result.error);  // 'Invalid recipient email address: invalid-email'
  console.log('Suggestion:', result.suggestion); // Helpful tip for fixing the error
  console.log('Request ID:', result.requestId);  // For support/debugging
}
```

## Next Steps

Now that you've sent your first email, you might want to:

* [Explore the full API reference](api-reference.md)
* [See more examples](examples.md)
* [Learn about error handling](error-handling.md)
* Check out advanced configuration options

## Need Help?

* 💬 [GitHub Issues](https://github.com/5ysc4ll/mailblock/issues)
* 📧 Email support: [contact@block-forge.de](mailto:contact@block-forge.de)
