# Webhook configuration

> Learn how to set up and configure webhooks to receive processed email data

Source: https://emailconnect.eu/help/webhook-configuration/

Webhooks are HTTP endpoints that receive processed email data from EmailConnect. This guide covers everything you need to know about setting up and managing webhooks.

## What are webhooks?

When an email is received by EmailConnect, it's processed and sent as an HTTP POST request to your webhook URL. This allows your application to:

- Receive email data in real-time
- Process emails programmatically
- Integrate with existing systems
- Trigger automated workflows

## Webhook data format

EmailConnect sends email data in JSON format:

```json
{
  "spam": {
    "score": -0.99,
    "engine": "rspamd"
  },
  "message": {
    "date": "2026-02-12T10:30:00.000Z",
    "sender": {
      "name": "Alice Martin",
      "email": "alice@example.com"
    },
    "content": {
      "text": "Hi team,\n\nPlease find the report attached.\n\nBest,\nAlice",
      "html": "<p>Hi team,</p><p>Please find the report attached.</p><p>Best,<br>Alice</p>",
      "markdown": "Hi team,\n\nPlease find the report attached.\n\nBest,\nAlice",
      "links": []
    },
    "subject": "Monthly report attached",
    "recipient": {
      "name": null,
      "email": "reports@yourdomain.com",
      "tag": null
    },
    "attachments": []
  },
  "integrity": {
    "contentHash": "a3f2b8c1...",
    "rawEmailHash": "9f8e7d6c..."
  },
  "classification": {
    "type": "normal",
    "confidence": "definite",
    "signals": []
  },
  "security": {
    "virusScan": {
      "scanned": true,
      "threatsFound": 0
    }
  }
}
```

## Setting up webhooks

### 1. Create a webhook endpoint

Your webhook endpoint should:
- Accept HTTP POST requests
- Return a 200 status code for successful processing
- Process requests within 30 seconds (timeout limit)
- Handle JSON content type

**Example webhook endpoint (Node.js/Express):**

```javascript
app.post('/webhook/emails', (req, res) => {
  const emailData = req.body;
  
  // Process the email data
  console.log('Received email:', emailData.subject);
  
  // Your processing logic here
  processEmail(emailData);
  
  // Return success response
  res.status(200).json({ success: true });
});
```

### 2. Add webhook in dashboard

1. Go to **Webhooks** in your dashboard
2. Click **Create Webhook**
3. Enter your webhook URL
4. Choose which events to receive
5. Test the webhook connection
6. Save the webhook

### 3. Configure webhook security

**Webhook Signatures:**
EmailConnect signs webhook requests following the [Standard Webhooks](https://github.com/standard-webhooks/standard-webhooks) convention. Verify signatures to ensure requests are authentic:

```javascript
const crypto = require('crypto');

function verifyWebhook(headers, rawBody, secret) {
  const signedContent = `${headers['webhook-id']}.${headers['webhook-timestamp']}.${rawBody}`;
  const secretBytes = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
  const expected = crypto.createHmac('sha256', secretBytes).update(signedContent).digest('base64');

  return headers['webhook-signature'].split(' ').some(sig => {
    const [v, val] = sig.split(',');
    return v === 'v1' && crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(val));
  });
}
```

## Webhook events

Configure which events trigger webhook calls:

- **Email Received**: New email processed
- **Delivery Failed**: Email processing failed
- **Bounce Received**: Bounce notification received
- **Spam Detected**: Email marked as spam

## Testing webhooks

### Built-in testing

Use the webhook testing feature in your dashboard:

1. Go to your webhook configuration
2. Click **Test Webhook**
3. Review the test response
4. Check your endpoint logs

### Manual testing

Send a test email to your alias and monitor:
- Your webhook endpoint logs
- EmailConnect delivery logs
- Response times and status codes

## Best practices

### Reliability

- **Idempotency**: Handle duplicate webhook calls gracefully
- **Timeouts**: Respond within 30 seconds to avoid retries
- **Error Handling**: Return appropriate HTTP status codes
- **Logging**: Log all webhook requests for debugging

### Security

- **HTTPS Only**: Always use HTTPS for webhook URLs
- **Signature Verification**: Verify webhook signatures
- **Rate Limiting**: Implement rate limiting on your endpoint

### Performance

- **Async Processing**: Process emails asynchronously when possible
- **Queue Systems**: Use queues for heavy processing
- **Database Optimization**: Optimize database operations
- **Monitoring**: Monitor webhook performance and errors

## Troubleshooting

### Common issues

**"Webhook timeout"**
- Ensure your endpoint responds within 30 seconds
- Move heavy processing to background jobs
- Check server performance and resources

**"Connection refused"**
- Verify your webhook URL is accessible from the internet
- Check firewall settings
- Ensure your server is running

**"Invalid signature"**
- Verify you're using the correct webhook secret
- Check signature calculation implementation
- Ensure payload is not modified before verification

### Replay and retry

> **Replay and Retry:** Paid plans can replay successful webhook deliveries or retry failed ones directly from the **Logs** view in the dashboard. This is useful for debugging without resending the original email.

### Debugging tools

- **Webhook logs**: Check delivery logs in your dashboard
- **Request inspection**: Use tools like ngrok for local testing
- **Network monitoring**: Monitor network connectivity and latency

## Advanced configuration

### Multiple webhooks

Each email is delivered to exactly one webhook: the webhook of the alias it was sent to, or of the domain's catch-all when no specific alias matches. Your account can have as many webhooks as you need, so different aliases can deliver to different endpoints (`support@` to your ticketing, `invoices@` to your accounting), and one webhook can serve several aliases.

There is no backup or fan-out delivery: retries go to the same webhook. To send one email to several systems, receive it once and pass it on from your own endpoint.

### Acting on conditions

To treat emails differently by sender, recipient, attachments or spam score, use [alias rules](https://emailconnect.eu/help/alias-rules/) (Maker and above): block or allow matching email, or tag it so your webhook can branch on the tag. To send a kind of email to a different endpoint, give it its own address and webhook.

## Next steps

- [Set up email aliases](https://emailconnect.eu/help/alias-options-explained/) to route emails to webhooks
- [Learn about email processing](https://emailconnect.eu/help/webhook-configuration/) options
- Configure attachment handling (contact support for advanced options)

## Need help?

Having webhook issues?
- Contact our support team at support@emailconnect.eu
- Review webhook logs in your dashboard
- Contact support with webhook URL and error details
