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

> ## Agent Instructions
> AhaSend stores all message data in the EU. See /facts.
> The API base URL is https://api.ahasend.com. Send the API key in the Authorization: Bearer header. See /api-reference/authentication.
> Use send.ahasend.com for SMTP. Ports 25, 587 and 2525 use STARTTLS. Port 465 is not supported. See /smtp.
> For send-only integrations, create an API Key v2 under Credentials → Add and scope it to messages:send:{your-domain}. See /send-api/credentials and /api-reference/scopes.

# Send Email in PHP via SMTP (PHPMailer, Laravel)

> Send email from PHP through the AhaSend SMTP relay with PHPMailer, Symfony Mailer or Laravel: STARTTLS settings, attachments and sandbox tests.

Send emails through AhaSend's SMTP servers using PHP with popular libraries like PHPMailer and Symfony Mailer. This guide covers everything from basic setup to advanced features like attachments and HTML content.

> [!WARNING]
>
> **Avoid Native mail() Function:** PHP's built-in `mail()` function is limited - it only works with localhost SMTP servers, doesn't support authentication or attachments, and makes HTML emails difficult to implement. Use the recommended libraries below instead.

## Prerequisites

Before sending, [verify your domain](https://ahasend.com/docs/domains.md) and [create an SMTP credential](https://ahasend.com/docs/smtp/credentials.md). Use a [sandbox credential](https://ahasend.com/docs/send-api/sandbox.md) for these examples so no email is delivered. Keep the username and password in your server's secret store.

Before you begin, ensure you have:

> [accordion] System Requirements
>
> * **PHP installed** on your system ([Download PHP](https://www.php.net/downloads))
> * **Composer** for package management ([Install Composer](https://getcomposer.org/))
> * Basic knowledge of PHP and command line usage

## Connection Settings

| Setting | Value |
| - | - |
| Host | `send.ahasend.com` |
| Ports with STARTTLS | 25, 587 and 2525 |
| Port with implicit TLS | 465 (TLS from the first byte, also called SSL/TLS or SMTPS) |
| Encryption | Required on every port: STARTTLS on 25, 587 and 2525, implicit TLS on 465 |
| Authentication | AUTH PLAIN after STARTTLS on 25, 587 and 2525; AUTH PLAIN or AUTH LOGIN on 465 |
| Username and password | Your SMTP credential, not an API key |

All message data is stored in the EU. See [SMTP limits](https://ahasend.com/docs/smtp.md#what-are-the-smtp-limits).

## PHPMailer Integration

PHPMailer is the most popular and feature-rich PHP email library, supporting HTML messages, attachments, and advanced SMTP features.

### Installation

Install PHPMailer using Composer:

```bash theme={null}
composer require phpmailer/phpmailer
```

### Basic Email Example

```php Basic PHPMailer Example theme={null}
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->isSMTP();
    $mail->Host       = 'send.ahasend.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'YOUR_SMTP_USERNAME';
    $mail->Password   = 'YOUR_SMTP_PASSWORD';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    // Recipients
    $mail->setFrom('hello@yourdomain.com', 'Your App Name');
    $mail->addAddress('user@example.com', 'John Doe');

    // Content
    $mail->isHTML(true);
    $mail->Subject = 'Welcome to our platform!';
    $mail->Body    = '<h1>Welcome!</h1><p>Thanks for signing up.</p>';
    $mail->AltBody = 'Welcome! Thanks for signing up.';

    $mail->send();
    echo 'Email sent successfully!';
} catch (Exception $e) {
    echo "Failed to send email: {$mail->ErrorInfo}";
}
?>
```

```php With Attachments theme={null}
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->isSMTP();
    $mail->Host       = 'send.ahasend.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'YOUR_SMTP_USERNAME';
    $mail->Password   = 'YOUR_SMTP_PASSWORD';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    // Recipients
    $mail->setFrom('hello@yourdomain.com', 'Your App Name');
    $mail->addAddress('user@example.com', 'John Doe');
    $mail->addReplyTo('support@yourdomain.com', 'Support');

    // Attachments
    $mail->addAttachment('/path/to/document.pdf', 'Invoice.pdf');
    $mail->addAttachment('/path/to/image.jpg');

    // Content
    $mail->isHTML(true);
    $mail->Subject = 'Your Invoice is Ready';
    $mail->Body    = '<h1>Invoice Attached</h1><p>Please find your invoice attached.</p>';
    $mail->AltBody = 'Your invoice is attached to this email.';

    $mail->send();
    echo 'Email with attachment sent successfully!';
} catch (Exception $e) {
    echo "Failed to send email: {$mail->ErrorInfo}";
}
?>
```

### PHPMailer with Special Headers

Add AhaSend's special headers for tracking, sandbox mode, and more:

The next block continues the basic PHPMailer example and uses its imports.

```php PHPMailer with Headers theme={null}
<?php
$mail = new PHPMailer(true);

try {
    // SMTP configuration (same as above)
    $mail->isSMTP();
    $mail->Host = 'send.ahasend.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'YOUR_SMTP_USERNAME';
    $mail->Password = 'YOUR_SMTP_PASSWORD';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    // Recipients and content
    $mail->setFrom('hello@yourdomain.com', 'Your App Name');
    $mail->addAddress('user@example.com', 'John Doe');

    // Add special headers
    $mail->addCustomHeader('ahasend-track-opens', 'true');
    $mail->addCustomHeader('ahasend-track-clicks', 'true');
    $mail->addCustomHeader('ahasend-tags', 'welcome,onboarding,php');

    // For sandbox testing:
    // $mail->addCustomHeader('AhaSend-Sandbox', 'true');

    $mail->isHTML(true);
    $mail->Subject = 'Welcome to our platform!';
    $mail->Body = '<h1>Welcome!</h1><p>Click <a href="https://yourdomain.com">here to get started</a>.</p>';

    $mail->send();
    echo 'Email sent with tracking enabled!';
} catch (Exception $e) {
    echo "Error: {$mail->ErrorInfo}";
}
?>
```

## Symfony Mailer Integration

Symfony Mailer is a modern, powerful email library that's part of the Symfony ecosystem and used by Laravel.

### Installation

Install Symfony Mailer using Composer:

```bash theme={null}
composer require symfony/mailer
```

### Basic Examples

```php Basic Symfony Mailer theme={null}
<?php
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mime\Email;

require 'vendor/autoload.php';

// Create transport using DSN
$dsn = 'smtp://YOUR_SMTP_USERNAME:YOUR_SMTP_PASSWORD@send.ahasend.com:587';
$transport = Transport::fromDsn($dsn);
$mailer = new Mailer($transport);

// Create email
$email = (new Email())
    ->from('hello@yourdomain.com')
    ->to('user@example.com')
    ->subject('Welcome to our platform!')
    ->text('Welcome! Thanks for signing up.')
    ->html('<h1>Welcome!</h1><p>Thanks for signing up.</p>');

try {
    $mailer->send($email);
    echo 'Email sent successfully!';
} catch (Exception $e) {
    echo 'Failed to send email: ' . $e->getMessage();
}
?>
```

```php With Headers & Attachments theme={null}
<?php
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mime\Email;

require 'vendor/autoload.php';

$dsn = 'smtp://YOUR_SMTP_USERNAME:YOUR_SMTP_PASSWORD@send.ahasend.com:587';
$transport = Transport::fromDsn($dsn);
$mailer = new Mailer($transport);

$email = (new Email())
    ->from('hello@yourdomain.com')
    ->to('user@example.com')
    ->subject('Your Invoice')
    ->html('<h1>Invoice Attached</h1><p>Please find your invoice attached.</p>')
    ->attachFromPath('/path/to/document.pdf', 'Invoice.pdf');

// Add custom headers
$email->getHeaders()
    ->addTextHeader('ahasend-track-opens', 'true')
    ->addTextHeader('ahasend-track-clicks', 'true')
    ->addTextHeader('ahasend-tags', 'invoice,billing');

$mailer->send($email);
echo 'Email with attachment sent!';
?>
```

## Laravel Configuration

Laravel uses Symfony Mailer internally. Configure AhaSend SMTP by updating your `.env` file:

### Environment Configuration

```env Laravel .env Configuration theme={null}
MAIL_MAILER=smtp
MAIL_HOST=send.ahasend.com
MAIL_PORT=587
MAIL_USERNAME=YOUR_SMTP_USERNAME
MAIL_PASSWORD=YOUR_SMTP_PASSWORD
MAIL_SCHEME=smtp
MAIL_FROM_ADDRESS=hello@yourdomain.com
MAIL_FROM_NAME="Your App Name"
```

### Sending Emails in Laravel

```php Basic Laravel Mail theme={null}
<?php
use Illuminate\Support\Facades\Mail;
use Illuminate\Mail\Message;

// Send a simple email
Mail::raw('Welcome! Thanks for signing up.', function (Message $message) {
    $message->to('user@example.com', 'John Doe')
            ->subject('Welcome to our platform!');
});

echo 'Email sent successfully!';
?>
```

```php Laravel with Custom Headers theme={null}
<?php
use Illuminate\Support\Facades\Mail;
use Illuminate\Mail\Message;

Mail::raw('Welcome! Thanks for signing up.', function (Message $message) {
    $message->to('user@example.com', 'John Doe')
            ->subject('Welcome to our platform!')
            ->getHeaders()
            ->addTextHeader('ahasend-track-opens', 'true')
            ->addTextHeader('ahasend-track-clicks', 'true')
            ->addTextHeader('ahasend-tags', 'welcome,laravel');
});

echo 'Email sent with tracking enabled!';
?>
```

## Best Practices

> [accordion] Error Handling
>
> **Always use try-catch blocks:**
>
> * Wrap email sending in try-catch statements
> * Log errors for debugging
> * Provide user-friendly error messages
> * Consider retry mechanisms for temporary failures

> [accordion] Security Considerations
>
> **Protect your credentials:**
>
> * Store SMTP credentials in environment variables
> * Never commit credentials to version control
> * Use different credentials for different environments
> * Regularly rotate SMTP passwords

> [accordion] Performance Optimization
>
> **Optimize for better performance:**
>
> * Use queue systems for bulk emails (Laravel Queues, etc.)
> * Reuse SMTP connections when sending multiple emails
> * Consider async sending for non-critical emails
> * Monitor sending rates to avoid limits

## Testing with Sandbox Mode

Use sandbox mode to test your PHP email integration safely:

The next block continues the basic PHPMailer example and uses its imports.

```php Sandbox Testing Examples theme={null}
<?php
// PHPMailer sandbox
$mail->addCustomHeader('AhaSend-Sandbox', 'true');
$mail->addCustomHeader('AhaSend-Sandbox-Result', 'deliver'); // or 'bounce', 'defer', etc.

// Symfony Mailer sandbox
$email->getHeaders()
    ->addTextHeader('AhaSend-Sandbox', 'true')
    ->addTextHeader('AhaSend-Sandbox-Result', 'deliver');

// Laravel sandbox
$message->getHeaders()
    ->addTextHeader('AhaSend-Sandbox', 'true')
    ->addTextHeader('AhaSend-Sandbox-Result', 'deliver');
?>
```

> [!NOTE]
>
> **Sandbox Benefits:** Emails sent in sandbox mode are free, trigger webhooks normally, and never actually deliver to recipients - perfect for development and testing.

## Troubleshooting

> [accordion] Authentication Failures
>
> **Common authentication issues:**
>
> * Verify SMTP username and password are correct
> * Ensure you're using SMTP credentials, not your dashboard login
> * Check that credentials haven't expired
> * Confirm domain is verified in AhaSend

> [accordion] Connection Problems
>
> **Network and connection issues:**
>
> * Try different ports: 587 (recommended), 25, or 2525
> * Use `PHPMailer::ENCRYPTION_STARTTLS` on ports 587, 25 and 2525, and `PHPMailer::ENCRYPTION_SMTPS` on port 465
> * Check firewall settings aren't blocking SMTP
> * Verify server allows outbound SMTP connections

> [accordion] Laravel-Specific Issues
>
> **Laravel configuration problems:**
>
> * Clear config cache: `php artisan config:clear`
> * Verify .env file syntax (no spaces around equals signs)
> * Check mail configuration: `php artisan config:show mail`
> * Test with `php artisan tinker` for debugging

## Resources

> [card] [PHPMailer Documentation](https://github.com/PHPMailer/PHPMailer)
>
> Official PHPMailer documentation and examples

> [card] [Symfony Mailer Documentation](https://symfony.com/doc/current/mailer.html)
>
> Complete Symfony Mailer documentation

> [card] [Laravel Mail Documentation](https://laravel.com/docs/mail)
>
> Laravel's email sending documentation

> [card] [AhaSend Support](mailto:support@ahasend.com)
>
> Get help from our engineering team

> [!TIP]
>
> **Pro Tip:** Start with sandbox mode when developing, use environment variables for credentials, and always provide both HTML and plain text versions of your emails for better compatibility.

For framework setup, use [Symfony](https://ahasend.com/docs/guides/symfony.md) or [Laravel](https://ahasend.com/docs/guides/laravel.md). Existing HTTP API integrations have their own [WordPress plugin](https://ahasend.com/docs/guides/wordpress.md) and [Drupal module](https://ahasend.com/docs/guides/drupal.md) guides.

## Related Guides

* Before sending: [verify your domain](https://ahasend.com/docs/domains.md) and [create an SMTP credential](https://ahasend.com/docs/smtp/credentials.md).
* Connection and message rules: [SMTP hosts, ports and limits](https://ahasend.com/docs/smtp.md), [special headers](https://ahasend.com/docs/smtp/special-headers.md), [sandbox mode](https://ahasend.com/docs/send-api/sandbox.md), [retention](https://ahasend.com/docs/retention.md) and [plan features](https://ahasend.com/docs/facts.md#plans-and-features).
* Other ways to send: [REST API](https://ahasend.com/docs/send-api/send-email.md), [AhaSend CLI](https://ahasend.com/docs/cli/quickstart.md), [Node.js SDK](https://ahasend.com/docs/guides/nodejs-sdk.md) and [Go SDK](https://ahasend.com/docs/guides/go-sdk.md).
* Delivery events: [webhook setup](https://ahasend.com/docs/integrations/webhooks.md) and [local webhook testing](https://ahasend.com/docs/cli/webhook-testing.md).


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