PHP Examples

PHP integration examples using the Metigan SDK. Learn how to send emails, manage contacts, and integrate Metigan into your PHP applications.

Installation

Composer

composer.jsonTerminal
1
composer require metigan/metigan-php

Basic Setup

basic.phpPhp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php

require 'vendor/autoload.php';

use Metigan\MetiganClient;
use Metigan\Exception\ApiException;
use Metigan\Exception\ValidationException;

// Initialize the client
$client = new MetiganClient(getenv('METIGAN_API_KEY'));

// Send email
try {
    $result = $client->email()->sendEmail(
        fromAddress: "Sender <sender@example.com>",
        recipients: ["recipient@example.com"],
        subject: "Hello!",
        content: "<h1>Hello!</h1><p>Thank you for signing up.</p>"
    );

    if ($result['success'] ?? false) {
        echo "Email sent successfully!
";
        // IMPORTANT: API returns fields in camelCase (emailsRemaining), not snake_case
        echo "Emails remaining: " . ($result['emailsRemaining'] ?? 'N/A') . "
";
    }
} catch (ValidationException $e) {
    echo "Validation Error: " . $e->getMessage() . "
";
} catch (ApiException $e) {
    echo "API Error: " . $e->getStatusCode() . " - " . $e->getMessage() . "
";
}

Sending Emails

Basic Email

send-email.phpPhp
1
2
3
4
5
6
7
8
9
10
11
12
13
$result = $client->email()->sendEmail(
    fromAddress: "sender@example.com",
    recipients: ["recipient@example.com"],
    subject: "Email Subject",
    content: "<h1>HTML Content</h1><p>This is the email body.</p>"
);

if ($result['success']) {
    echo "Email sent successfully!
";
    echo "Emails remaining: " . $result['emailsRemaining'] . "
";
}

Email with CC and BCC

send-email-cc.phpPhp
1
2
3
4
5
6
7
8
9
$result = $client->email()->sendEmail(
    fromAddress: "company@email.com",
    recipients: ["main@email.com"],
    subject: "Meeting",
    content: "Email content",
    cc: ["copy@email.com"],
    bcc: ["hidden-copy@email.com"],
    replyTo: "reply-here@email.com"
);

Email with Attachments

send-email-attachment.phpPhp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$fileData = file_get_contents("document.pdf");

$result = $client->email()->sendEmail(
    fromAddress: "company@email.com",
    recipients: ["customer@email.com"],
    subject: "Important Document",
    content: "Please find the document attached.",
    attachments: [
        [
            'content' => $fileData,
            'filename' => 'document.pdf',
            'contentType' => 'application/pdf'
        ]
    ]
);

Email with Template

send-email-template.phpPhp
1
2
3
4
5
6
7
8
9
10
$result = $client->email()->sendEmailWithTemplate(
    templateId: "template-123",
    variables: [
        'name' => 'John Doe',
        'company' => 'Acme Inc'
    ],
    fromAddress: "sender@example.com",
    recipients: ["recipient@example.com"],
    replyTo: "reply@example.com"
);

Managing Contacts

Create Contact

create-contact.phpPhp
1
2
3
4
5
6
7
8
$contact = $client->contacts()->create(
    email: "new@email.com",
    audienceId: "audience-123",
    firstName: "Jane",
    lastName: "Doe",
    phone: "+1234567890",
    tags: ["customer", "newsletter"]
);

Get Contact

get-contact.phpPhp
1
2
$contact = $client->contacts()->get("contact-456");
echo $contact['email'] . ": " . $contact['firstName'];

List Contacts

list-contacts.phpPhp
1
2
3
4
5
6
7
8
9
10
11
$result = $client->contacts()->list(
    audienceId: "audience-123",
    status: "subscribed",
    page: 1,
    limit: 50
);

foreach ($result['contacts'] ?? [] as $contact) {
    echo $contact['email'] . ": " . ($contact['firstName'] ?? 'N/A') . "
";
}

Update Contact

update-contact.phpPhp
1
2
3
4
5
$updated = $client->contacts()->update(
    contactId: "contact-456",
    firstName: "Jane Marie",
    tags: ["customer", "vip"]
);

Manage Subscription

manage-subscription.phpPhp
1
2
3
4
5
// Subscribe
$client->contacts()->subscribe("contact-456");

// Unsubscribe
$client->contacts()->unsubscribe("contact-456");

Managing Audiences

Create Audience

create-audience.phpPhp
1
2
3
4
$audience = $client->audiences()->create(
    name: "Main Newsletter",
    description: "Main subscriber list"
);

List Audiences

list-audiences.phpPhp
1
2
3
4
5
6
$result = $client->audiences()->list(page: 1, limit: 10);

foreach ($result['audiences'] ?? [] as $audience) {
    echo $audience['name'] . ": " . ($audience['count'] ?? 0) . " contacts
";
}

Audience Stats

audience-stats.phpPhp
1
2
3
4
5
$stats = $client->audiences()->getStats("audience-123");
echo "Total: " . ($stats['total'] ?? 0) . "
";
echo "Subscribed: " . ($stats['subscribed'] ?? 0) . "
";

Error Handling

error-handling.phpPhp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use Metigan\Exception\ApiException;
use Metigan\Exception\ValidationException;

try {
    $result = $client->email()->sendEmail(/* ... */);
} catch (ValidationException $e) {
    echo "Validation Error: " . $e->getMessage() . "
";
    if ($e->getField()) {
        echo "Field: " . $e->getField() . "
";
    }
} catch (ApiException $e) {
    echo "API Error: " . $e->getStatusCode() . " - " . $e->getMessage() . "
";
} catch (Exception $e) {
    echo "Unknown error: " . $e->getMessage() . "
";
}

Advanced Configuration

config.phpPhp
1
2
3
4
5
6
7
$client = new MetiganClient(
    apiKey: "your-api-key",
    timeout: 30,        // Optional, defaults to 30 seconds
    retryCount: 3,      // Optional, defaults to 3
    retryDelay: 2,      // Optional, defaults to 2 seconds
    debug: false        // Optional, defaults to false
);
Response Format

The API returns all fields in camelCase format. Always use camelCase when accessing response data:

  • emailsRemaining (not emails_remaining)
  • recipientCount (not recipient_count)
  • successfulEmails (not successful_emails)