# Email configuration

Send emails through Cakemail's `/v2/emails` API endpoint using standard SMTP protocol. This SMTP gateway allows you to leverage the full power of Cakemail's Email API without modifying your existing SMTP-based applications.

## Overview

This SMTP gateway provides a familiar interface for developers already using SMTP in their applications. Simply configure your SMTP client to use Cakemail's SMTP server with your account credentials.

**Benefits:**
- Use existing SMTP libraries and code
- Minimal changes to legacy applications
- Standard protocol with wide language support
- Industry-leading deliverability

## Email API Subscription Required

Before using SMTP, you have to have an active Email API account, with a valid Email API subscription.

Learn more about Email API pricing and subscriptions at [cakemail.com/solutions/email-api](https://www.cakemail.com/solutions/email-api)

## SMTP Configuration

### Server Details

- **Host:** `smtp.cakemail.dev`
- **Port:** `465` (SMTPS - SMTP over SSL/TLS) or `587` (STARTTLS)
- **Authentication:** Required (your Cakemail username and password)
- **Encryption:** SSL/TLS on port 465; STARTTLS on port 587

Both ports send the same way. Use port 587 if your SMTP client or network supports only STARTTLS.

### Authentication

Use your Cakemail account credentials:

- **Username:** Your Cakemail account username
- **Password:** Your Cakemail account password

## Prerequisites

### Sender Requirements

Before sending emails, your sender address must be:

- **Registered** in your Cakemail account
- **Validated** through the email verification process
- **Authenticated** with proper SPF/DKIM records
- **Tracking Domain** branded on your proper domain

The sender address in the `From:` header must match a validated sender in your Cakemail account. Emails from unvalidated senders will be rejected.

Learn more: [Authenticating Domains](/docs/senders/authenticating-domains)

### List ID

Contact management is required for compliance and bounce handling. You'll need a List ID from your Cakemail account. Find your default list or create a new one through the [Lists API endpoint](/guides/sending-emails-rest-api#find-your-list-id).

## Required Headers

To use the SMTP to Email API gateway, include these headers in your email:

### x-email-api-enabled

**Format:** `x-email-api-enabled: true`

Sends the message through the Email API. Every SMTP message needs it, unless your SMTP username sets `emailApi:true` (see [Embedding Parameters in Your SMTP Username](#advanced-embedding-parameters-in-your-smtp-username)).

### x-list-id

**Format:** `x-list-id: <list-id>`

Associates the email with a Cakemail list. This header is required by default.

**Why x-list-id is required:**

- **Consent management**: Maintains compliance with email regulations
- **Bounce handling**: Automatically processes bounces and unsubscribes
- **Contact management**: Recipients not present in the list are automatically added

If your use case justifies not using a list ID, contact Cakemail support at [support@cakemail.com](mailto:support@cakemail.com) to discuss alternatives.

### Example

```
x-email-api-enabled: true
x-list-id: 9234980
```

## Optional Headers

### x-email-api-type

**Format:** `x-email-api-type: <marketing|transactional>`

Specifies the type of communication. Defaults to `marketing` if not provided.

- `marketing`: Promotional content, newsletters, campaigns
- `transactional`: Order confirmations, password resets, receipts

### x-tags

**Format:** `x-tags: tag1,tag2`

Comma-separated list of tags for organizing and filtering emails in your Cakemail account.

### Example

```
x-email-api-type: transactional
x-tags: welcome,onboarding
```

## Email Structure

### Standard Headers

Your email must include standard SMTP headers:

- **`From:`** Sender email address (must match a validated sender)
- **`To:`** Recipient email address (single recipient only)
- **`Subject:`** Email subject line

**Important:** Only one recipient is allowed per SMTP transaction. To send to multiple recipients, make separate SMTP calls for each recipient.

### Complete Example

```
From: sender@example.com
To: recipient@example.com
Subject: Welcome to Our Service
x-email-api-enabled: true
x-list-id: 9234980
x-email-api-type: marketing

Hello,

Welcome to our service! We're excited to have you on board.

Best regards,
The Team
```

## Quick Start Example

### Using curl

```shell
curl -v \
    --mail-from 'sender@example.com' \
    --mail-rcpt 'recipient@example.com' \
    smtps://smtp.cakemail.dev:465 \
    --user "your-username:your-password" \
    --upload-file - <<EOF
From: sender@example.com
To: recipient@example.com
Subject: Test Email
x-email-api-enabled: true
x-list-id: 9234980

This is the email body content.
EOF
```

## Code Examples

### Python (smtplib)

```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

smtp_server = "smtp.cakemail.dev"
smtp_port = 465
username = "your-username"
password = "your-password"

msg = MIMEMultipart()
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg['Subject'] = 'Test Email'
msg['x-email-api-enabled'] = 'true'
msg['x-list-id'] = '9234980'

body = "This is the email body content."
msg.attach(MIMEText(body, 'plain'))

# Send email
with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
    server.login(username, password)
    server.send_message(msg)
    print("Email sent successfully!")
```

### Node.js (nodemailer)

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

const transporter = nodemailer.createTransport({
  host: 'smtp.cakemail.dev',
  port: 465,
  secure: true, // use SSL/TLS
  auth: {
    user: 'your-username',
    pass: 'your-password'
  }
});

const mailOptions = {
  from: 'sender@example.com',
  to: 'recipient@example.com',
  subject: 'Test Email',
  text: 'This is the email body content.',
  headers: {
    'x-email-api-enabled': 'true',
    'x-list-id': '9234980'
  }
};

transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    console.error('Error:', error);
  } else {
    console.log('Email sent:', info.response);
  }
});
```

### PHP (PHPMailer)

```php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->isSMTP();
    $mail->Host       = 'smtp.cakemail.dev';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'your-username';
    $mail->Password   = 'your-password';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    $mail->Port       = 465;

    // Recipients
    $mail->setFrom('sender@example.com');
    $mail->addAddress('recipient@example.com');

    // Custom headers
    $mail->addCustomHeader('x-email-api-enabled', 'true');
    $mail->addCustomHeader('x-list-id', '9234980');

    // Content
    $mail->Subject = 'Test Email';
    $mail->Body    = 'This is the email body content.';

    $mail->send();
    echo 'Email sent successfully!';
} catch (Exception $e) {
    echo "Email could not be sent. Error: {$mail->ErrorInfo}";
}
?>
```

## Advanced: Embedding Parameters in Your SMTP Username

The Cakemail SMTP relay lets you control sending behavior directly from your SMTP username — no custom email headers required. This is useful when your email client or integration doesn't support custom headers.

### How It Works

Wrap your parameters in parentheses and insert them between the `@` sign and the domain part of your username:

```
your-email@(parameters)yourdomain.com
```

The server strips the parameters before authenticating, so your actual Cakemail credentials remain `your-email@yourdomain.com`.

### Syntax Rules

| Separator | Purpose |
|-----------|---------|
| `;` (semicolon) | Separates different parameters |
| `,` (comma) | Separates multiple values within a parameter (e.g. tags) |

### Available Parameters

#### `emailApi:true`
Sends every email in the session through the Email API, in place of the `x-email-api-enabled: true` header. **Required** when your emails don't carry that header, and if you want to use `listId` or `tags`.

#### `listId:<id>`
Associates all emails in the session with a specific contact list. Only applied when `emailApi:true`.

#### `tags:<tag1>,<tag2>,...`
Applies one or more tags to all emails in the session. Only applied when `emailApi:true`.

#### `type:marketing|transactional`
Sets the email type for all emails in the session, like the `x-email-api-type` header.

#### `trackOpens:true|false`
Enables or disables open tracking for all emails in the session.

#### `trackClicks:true|false`
Enables or disables click tracking (both HTML and plain-text links) for all emails in the session.

#### `senderId:<id>`
Bypasses the automatic sender lookup by specifying a known sender ID directly. Useful for performance optimization when you already know your sender ID.

### Username Parameter Examples

**Send via Email API to a specific list:**
```
john@(emailApi:true;listId:999)example.com
```

**Send via Email API with tags:**
```
john@(emailApi:true;listId:999;tags:newsletter,june-campaign)example.com
```

**Mark all emails as transactional:**
```
john@(emailApi:true;listId:999;type:transactional)example.com
```

**Enable open and click tracking:**
```
john@(emailApi:true;listId:999;trackOpens:true;trackClicks:true)example.com
```

**Skip sender lookup with a known sender ID:**
```
john@(emailApi:true;listId:999;senderId:12345)example.com
```

**All options combined:**
```
john@(emailApi:true;listId:999;tags:marketing,q4;type:transactional;trackOpens:true;trackClicks:true;senderId:12345)example.com
```

### Priority: Headers vs. Username Parameters

If your email also includes `x-*` custom headers (e.g. `x-list-id`, `x-tags`, `x-sender-id`), the **header values take precedence** over username parameters — except for tags, which are **merged** (duplicates removed) when the Email API is enabled.

### Username Parameter Notes

- `listId` and `tags` are ignored unless `emailApi:true` is also set.
- Parameters affect the entire session — every email sent after authentication will use these settings.

## Troubleshooting

### Authentication Failed

**Problem:** Unable to authenticate with SMTP server

**Solutions:**
- Verify your Cakemail username and password are correct
- Ensure your account has API access enabled
- Check that you're using the correct authentication method

### Connection Refused

**Problem:** Cannot connect to SMTP server

**Solutions:**
- Confirm you're using port 465 with SSL/TLS, or port 587 with STARTTLS
- Check if your firewall allows outbound connections on that port
- Verify the hostname is `smtp.cakemail.dev`

### Email Not Delivered

**Problem:** Email sent but not received

**Solutions:**
- Ensure `x-email-api-enabled: true` header is included
- Verify the `From` and `To` addresses are valid
- Confirm the sender email is registered, validated, and authenticated in your Cakemail account
- Check that the `x-list-id` header contains a valid list ID
- Review spam/junk folders

### Verbose Mode

Use curl's `-v` flag for detailed connection information:

```shell
curl -v \
    --mail-from 'sender@example.com' \
    --mail-rcpt 'recipient@example.com' \
    smtps://smtp.cakemail.dev:465 \
    --user "username:password" \
    --upload-file message.txt
```

## Limitations

### Single Recipient Per SMTP Call

You cannot use multiple recipients in a single SMTP transaction. Each email must be sent to one recipient at a time using `--mail-rcpt` with a single address.

To send to multiple recipients, make separate SMTP calls for each recipient address.

### Attachments Not Enabled by Default

Email attachments are disabled by default. Contact [support@cakemail.com](mailto:support@cakemail.com) to enable attachment support for your account.

## Related Documentation

- [Getting Started with Email API](/guides/getting-started-email-api) - Overview and choosing integration method
- [Sending Emails via REST API](/guides/sending-emails-rest-api) - Alternative REST integration
- [Email API Reference](/guides/email-api-reference) - Quick reference guide
- [Authenticating Domains](/docs/senders/authenticating-domains) - SPF/DKIM setup
- [Managing Contact Lists](/docs/audience/managing-contact-lists) - Contact management
