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

# Security

> Secure your inbound email pipeline in Lettr by verifying the auth token sent to your forwarding URL and handling external mail safely.

Receiving emails from external sources introduces security considerations. This guide covers best practices for securing your inbound email processing pipeline. Apart from the auth token, everything here runs in your own handler: Lettr posts inbound mail to your forwarding URL as received and doesn't sanitize, scan or filter it.

## Forwarding URL Security

### Verify the Auth Token

Always verify that requests to your forwarding URL come from Lettr, not malicious actors. When you create an inbound domain, or later on the domain's **Mail Forwarding** card, set an **Auth token**. It is sent with every request in the `X-MessageSystems-Webhook-Token` header. Compare it against your stored value and reject anything that doesn't match:

```javascript theme={null}
import crypto from 'node:crypto';
import express from 'express';

function verifyInboundToken(req, res, next) {
  const token = req.get('X-MessageSystems-Webhook-Token') ?? '';
  const expected = process.env.INBOUND_AUTH_TOKEN;

  // Constant-time comparison to avoid timing attacks
  if (
    token.length !== expected.length ||
    !crypto.timingSafeEqual(Buffer.from(token), Buffer.from(expected))
  ) {
    return res.sendStatus(401);
  }

  next();
}

app.post('/webhooks/inbound', verifyInboundToken, express.json({ limit: '50mb' }), async (req, res) => {
  for (const event of req.body) {
    const relay = event.msys?.relay_message;
    if (!relay) continue;

    await processEmail(relay);
  }

  res.sendStatus(200);
});
```

> [!NOTE]
>
> Lettr never shows your auth token again after you save it, so keep your own copy (for example in an environment variable). To rotate it, enter a new token on the **Mail Forwarding** card and click **Save forwarding URL**. Leaving the field blank keeps the token that is already set.

### Don't Rely on IP Allowlisting

Inbound mail is posted to your forwarding URL by SparkPost, the mail infrastructure behind Lettr's inbound servers, and SparkPost publishes no fixed source IP addresses. An IP allowlist can't reliably identify these requests, so use the auth token instead.

If your endpoint sits behind Cloudflare or another firewall/WAF, allow server-to-server `POST` requests on your forwarding URL's path. Otherwise the firewall may answer with a challenge page, and a non-`2xx` response makes the forwarding URL test fail when you create the domain or save a new URL.

## Input Validation

### Validate Email Addresses

Never trust email addresses from inbound emails. `msg_from`, `friendly_from` and the address headers are all set by the sender:

```javascript theme={null}
function validateEmailAddress(email) {
  if (!email || typeof email !== 'string') {
    return false;
  }

  // Basic format check
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(email)) {
    return false;
  }

  // Length limits
  if (email.length > 254) {
    return false;
  }

  const [localPart, domain] = email.split('@');
  if (localPart.length > 64 || domain.length > 255) {
    return false;
  }

  return true;
}
```

### Sanitize Email Content

Sanitize HTML content before displaying or storing:

```javascript theme={null}
import DOMPurify from 'isomorphic-dompurify';

function sanitizeHtml(html) {
  return DOMPurify.sanitize(html, {
    ALLOWED_TAGS: [
      'p', 'br', 'b', 'i', 'u', 'strong', 'em',
      'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
      'ul', 'ol', 'li', 'a', 'img', 'blockquote',
      'table', 'thead', 'tbody', 'tr', 'th', 'td',
      'span', 'div'
    ],
    ALLOWED_ATTR: ['href', 'src', 'alt', 'class', 'style'],
    ALLOW_DATA_ATTR: false,
    FORBID_TAGS: ['script', 'iframe', 'object', 'embed', 'form'],
    FORBID_ATTR: ['onerror', 'onload', 'onclick']
  });
}

app.post('/webhooks/inbound', verifyInboundToken, express.json({ limit: '50mb' }), async (req, res) => {
  for (const event of req.body) {
    const relay = event.msys?.relay_message;
    if (!relay) continue;

    // Either body can be missing
    const { html, text } = relay.content;

    // Sanitize before storing
    const safeHtml = html ? sanitizeHtml(html) : null;
    const safeText = text ? escapeHtml(text) : null;

    await storeEmail({ html: safeHtml, text: safeText });
  }

  res.sendStatus(200);
});
```

### Validate and Sanitize Filenames

Attachment filenames come from the sender. Never use them directly as paths:

```javascript theme={null}
import crypto from 'node:crypto';
import path from 'node:path';

function sanitizeFilename(filename) {
  if (!filename || typeof filename !== 'string') {
    return 'unnamed_file';
  }

  // Remove directory traversal attempts
  let safe = path.basename(filename);

  // Remove dangerous characters
  safe = safe.replace(/[<>:"/\\|?*\x00-\x1f]/g, '_');

  // Limit length
  safe = safe.substring(0, 200);

  // Ensure not empty
  if (!safe || safe === '.' || safe === '..') {
    safe = 'unnamed_file';
  }

  return safe;
}

// Generate unique filenames to prevent overwrites
function generateSafeFilename(originalFilename) {
  const safe = sanitizeFilename(originalFilename);
  const ext = path.extname(safe);
  const base = path.basename(safe, ext);
  const timestamp = Date.now();
  const random = crypto.randomBytes(4).toString('hex');

  return `${base}_${timestamp}_${random}${ext}`;
}
```

## Attachment Security

### Extract Attachments From the Raw Message

The payload has no attachments array and no attachment URLs. Attachments exist only inside the raw MIME message in `content.email_rfc822`, so your handler parses it with a MIME library such as [mailparser](https://nodemailer.com/extras/mailparser/). Every check below runs on the parsed attachments:

```javascript theme={null}
import { simpleParser } from 'mailparser';

async function extractAttachments(relay) {
  const { content } = relay;
  const raw = content.email_rfc822_is_base64
    ? Buffer.from(content.email_rfc822, 'base64')
    : content.email_rfc822;

  const parsed = await simpleParser(raw);

  // Each attachment has filename, contentType, size and content (a Buffer)
  return parsed.attachments;
}
```

Lettr doesn't store inbound messages or attachments, so validate and save what you need while handling the request, or from a queue job that received the payload. See [Attachments](https://docs.lettr.com/learn/inbound/attachments.md) for more.

### Validate File Types

Never trust the declared content type. Detect the real type from the file's bytes:

```javascript theme={null}
import { fileTypeFromBuffer } from 'file-type';

const ALLOWED_TYPES = new Map([
  ['application/pdf', ['.pdf']],
  ['image/jpeg', ['.jpg', '.jpeg']],
  ['image/png', ['.png']],
  ['image/gif', ['.gif']],
  ['text/plain', ['.txt']],
  ['text/csv', ['.csv']]
]);

async function validateAttachment(attachment) {
  const buffer = attachment.content;

  // Detect actual file type from content
  const detected = await fileTypeFromBuffer(buffer);

  if (!detected) {
    // Could be a text file, which has no magic bytes
    if (attachment.contentType.startsWith('text/')) {
      return { valid: true, type: attachment.contentType };
    }
    return { valid: false, reason: 'Unknown file type' };
  }

  // Check if type is allowed
  if (!ALLOWED_TYPES.has(detected.mime)) {
    return { valid: false, reason: `File type not allowed: ${detected.mime}` };
  }

  // Verify declared type matches detected type
  if (detected.mime !== attachment.contentType) {
    console.warn(
      `Content-Type mismatch: declared ${attachment.contentType}, detected ${detected.mime}`
    );
    // Use detected type, not declared type
  }

  return { valid: true, type: detected.mime };
}
```

### Scan for Malware

Integrate with a virus scanner:

```javascript theme={null}
import ClamScan from 'clamscan';

const clamscan = await new ClamScan().init({
  clamdscan: {
    host: process.env.CLAMAV_HOST || 'localhost',
    port: 3310
  }
});

async function scanForMalware(attachment) {
  try {
    const { isInfected, viruses } = await clamscan.scanBuffer(attachment.content);

    if (isInfected) {
      console.error(`Malware detected in ${attachment.filename}: ${viruses.join(', ')}`);
      return {
        safe: false,
        threats: viruses
      };
    }

    return { safe: true };
  } catch (error) {
    console.error('Virus scan failed:', error);
    // Fail closed - treat as unsafe if scanning fails
    return { safe: false, error: 'Scan failed' };
  }
}
```

### Limit File Sizes

Set your own size limits to prevent resource exhaustion. The numbers below are example values for your application, not Lettr limits:

```javascript theme={null}
const MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024; // 10 MB
const MAX_TOTAL_SIZE = 25 * 1024 * 1024; // 25 MB

function validateAttachmentSizes(attachments) {
  let totalSize = 0;

  for (const attachment of attachments) {
    if (attachment.size > MAX_ATTACHMENT_SIZE) {
      return {
        valid: false,
        reason: `Attachment ${attachment.filename} exceeds size limit`
      };
    }
    totalSize += attachment.size;
  }

  if (totalSize > MAX_TOTAL_SIZE) {
    return {
      valid: false,
      reason: 'Total attachment size exceeds limit'
    };
  }

  return { valid: true };
}
```

Putting the attachment checks together in your handler:

```javascript theme={null}
app.post('/webhooks/inbound', verifyInboundToken, express.json({ limit: '50mb' }), async (req, res) => {
  for (const event of req.body) {
    const relay = event.msys?.relay_message;
    if (!relay) continue;

    const attachments = await extractAttachments(relay);

    if (!validateAttachmentSizes(attachments).valid) {
      await logRejectedEmail(relay, 'Attachments too large');
      continue;
    }

    for (const attachment of attachments) {
      const typeCheck = await validateAttachment(attachment);
      const scan = typeCheck.valid ? await scanForMalware(attachment) : { safe: false };

      if (typeCheck.valid && scan.safe) {
        await saveToStorage(generateSafeFilename(attachment.filename), attachment.content);
      }
    }

    await processEmail(relay);
  }

  res.sendStatus(200);
});
```

For large messages or slow scanners, acknowledge the request first and run these checks from a queue.

## Content Security

### Prevent XSS in Displayed Emails

When displaying email content in a web interface:

```javascript theme={null}
// Use CSP headers
app.use((req, res, next) => {
  res.setHeader(
    'Content-Security-Policy',
    "default-src 'self'; img-src 'self' https:; style-src 'self' 'unsafe-inline'"
  );
  next();
});

// Render emails in sandboxed iframe
function renderEmailHtml(sanitizedHtml) {
  return `
    <iframe
      sandbox="allow-same-origin"
      srcdoc="${escapeAttribute(sanitizedHtml)}"
      style="width: 100%; height: 500px; border: none;"
    ></iframe>
  `;
}
```

### Block Tracking Pixels

Strip tracking pixels from received emails:

```javascript theme={null}
function removeTrackingPixels(html) {
  // Remove 1x1 images (common tracking pixels)
  html = html.replace(
    /<img[^>]*(?:width|height)\s*=\s*["']?1["']?[^>]*>/gi,
    ''
  );

  // Remove images from known tracking domains
  const trackingDomains = [
    'mailtrack.io',
    'pixel.watch',
    'track.customer.io',
    'open.convertkit.com'
  ];

  for (const domain of trackingDomains) {
    const regex = new RegExp(`<img[^>]*${domain}[^>]*>`, 'gi');
    html = html.replace(regex, '');
  }

  return html;
}
```

## Rate Limiting

Protect against email flooding by limiting how many messages one sender, one sender domain, or all senders together can push through your pipeline:

```javascript theme={null}
import { RateLimiterRedis } from 'rate-limiter-flexible';
import Redis from 'ioredis';

const redis = new Redis(process.env.REDIS_URL);

const senderLimiter = new RateLimiterRedis({
  storeClient: redis,
  keyPrefix: 'inbound_sender',
  points: 100, // 100 emails
  duration: 3600 // per hour
});

const domainLimiter = new RateLimiterRedis({
  storeClient: redis,
  keyPrefix: 'inbound_domain',
  points: 500,
  duration: 3600
});

const globalLimiter = new RateLimiterRedis({
  storeClient: redis,
  keyPrefix: 'inbound_global',
  points: 10000,
  duration: 3600
});

async function checkRateLimits(relay) {
  const sender = (relay.msg_from || 'unknown').toLowerCase();
  const domain = sender.split('@')[1] || 'unknown';

  try {
    await Promise.all([
      senderLimiter.consume(sender),
      domainLimiter.consume(domain),
      globalLimiter.consume('global')
    ]);
    return { allowed: true };
  } catch (error) {
    return {
      allowed: false,
      reason: 'Rate limit exceeded',
      retryAfter: Math.ceil(error.msBeforeNext / 1000)
    };
  }
}
```

Still answer the request with a `2xx` when you drop a rate-limited message. Your response doesn't reach the sender, so an error status can't push the mail back to them.

## Logging and Monitoring

### Audit Logging

Log all inbound email processing. The payload has no event ID, so use the `Message-ID` header to identify a message:

```javascript theme={null}
function getHeader(relay, name) {
  const wanted = name.toLowerCase();
  for (const header of relay.content?.headers ?? []) {
    for (const [key, value] of Object.entries(header)) {
      if (key.toLowerCase() === wanted) return value;
    }
  }
  return undefined;
}

async function logInboundEmail(relay, attachments, result) {
  await auditLog.create({
    type: 'inbound_email',
    messageId: getHeader(relay, 'Message-ID'),
    from: relay.msg_from,
    to: relay.rcpt_to,
    subject: relay.content?.subject?.substring(0, 100),
    attachmentCount: attachments.length,
    result: result.status,
    processingTime: result.duration,
    timestamp: new Date()
  });
}
```

### Anomaly Detection

Monitor for suspicious patterns:

```javascript theme={null}
class AnomalyDetector {
  constructor() {
    this.senderHistory = new Map();
  }

  analyze(relay, attachments) {
    const sender = (relay.msg_from || 'unknown').toLowerCase();
    const alerts = [];

    // Track sender frequency
    const history = this.senderHistory.get(sender) || { count: 0, firstSeen: Date.now() };
    history.count++;
    this.senderHistory.set(sender, history);

    // New sender sending many emails quickly
    if (history.count > 10 && Date.now() - history.firstSeen < 60000) {
      alerts.push({
        type: 'rapid_sender',
        sender,
        count: history.count,
        duration: Date.now() - history.firstSeen
      });
    }

    // Unusual attachment patterns (attachments parsed from content.email_rfc822)
    if (attachments.length > 5) {
      alerts.push({
        type: 'many_attachments',
        sender,
        count: attachments.length
      });
    }

    return alerts;
  }
}
```

## Security Checklist

> [accordion] Forwarding URL Security
>
> * [ ] Set an auth token and verify the `X-MessageSystems-Webhook-Token` header on every request
> * [ ] Store the token securely in environment variables
> * [ ] Use HTTPS for your forwarding URL
> * [ ] Allow server-to-server `POST` requests through your firewall or WAF instead of relying on an IP allowlist

> [accordion] Input Validation
>
> * [ ] Validate all email addresses
> * [ ] Sanitize HTML content before storage/display
> * [ ] Sanitize filenames before use
> * [ ] Validate attachment content types

> [accordion] Attachment Security
>
> * [ ] Parse attachments from `content.email_rfc822` with a MIME library
> * [ ] Verify file types from content, not headers
> * [ ] Scan attachments for malware
> * [ ] Enforce your own size limits
> * [ ] Store attachments outside web root

> [accordion] Monitoring
>
> * [ ] Log all inbound email processing
> * [ ] Monitor for rate limit violations
> * [ ] Alert on anomalous patterns
> * [ ] Track your own spam filtering decisions

> [!WARNING]
>
> Never trust any data from inbound emails. Senders can forge headers, spoof addresses, and include malicious content. Always validate and sanitize everything.

## Related Topics

> [card] [Inbound Setup](https://docs.lettr.com/learn/inbound/setup.md)
>
> Set the forwarding URL and auth token

> [card] [Spam Filtering](https://docs.lettr.com/learn/inbound/spam-filtering.md)
>
> Handle spam in your own handler

> [card] [Attachments](https://docs.lettr.com/learn/inbound/attachments.md)
>
> Handle attachments safely

> [card] [Best Practices](https://docs.lettr.com/learn/inbound/best-practices.md)
>
> Overall best practices


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.