Primordyx Framework Documentation

MailgunMailer
in package

Mailgun HTTP API email sending service with attachment support

A comprehensive email service class that integrates with the Mailgun HTTP API to send emails with support for HTML/text content, multiple recipients, attachments, and detailed response tracking. Provides fluent interface for email composition and automatic error handling with EventManager integration.

Key Features

  • HTML and plain text email support
  • Multiple recipients (TO, CC, BCC)
  • File attachments with CURL integration
  • Comprehensive error handling and response tracking
  • EventManager integration for logging and debugging
  • Configuration fallback from Bundle::appConfig()

Configuration Requirements

Requires Mailgun configuration in application INI file:

  • endpoint: Mailgun API endpoint URL
  • api_key: Mailgun API key for authentication
  • domain: Mailgun sending domain
  • suffix: API path suffix (typically '/messages')

Response Tracking

After sending, the instance contains complete response information:

  • HTTP status codes and error messages
  • Mailgun message ID for successful sends
  • Full HttpResult object for detailed analysis
Tags
since
1.0.0
example

Basic Email Sending

$mailer = new MailgunMailer();
$mailer->setFrom('sender@example.com')
       ->setTo('recipient@example.com')
       ->setSubject('Test Email')
       ->setText('Hello World!');
$messageId = $mailer->send();
example

Email with Attachments

$mailer = new MailgunMailer();
$mailer->setFrom('sender@example.com')
       ->setTo('recipient@example.com')
       ->setSubject('Report Attached')
       ->setHtml('<p>Please see attached report.</p>')
       ->addAttachment('/path/to/report.pdf');
$messageId = $mailer->send(true); // With verbose logging
example

Multiple Recipients

$mailer = new MailgunMailer();
$mailer->setFrom('newsletter@company.com')
       ->setTo('primary@example.com')
       ->setCc('manager@company.com,backup@company.com')
       ->setBcc('archive@company.com')
       ->setSubject('Monthly Newsletter')
       ->setHtml($htmlContent);
$messageId = $mailer->send();

Table of Contents

Properties

$httpClientConfig  : HttpClientConfig|null
HTTP client configuration used for Mailgun API requests
$httpCode  : int
HTTP status code from Mailgun API response
$httpResult  : HttpResult|null
Complete HTTP response object from Mailgun API call
$mailgun_id  : string
Mailgun message ID returned after successful email sending
$mailgun_message  : string
Mailgun response message from API call
$apiKey  : string
$attachments  : array<string|int, mixed>
$bcc  : string
$cc  : string
$domain  : string
$endpoint  : string
$from  : string
$html  : string
$replyTo  : string
$subject  : string
$suffix  : string
$text  : string
$to  : string

Methods

__construct()  : mixed
Initialize MailgunMailer with API configuration and validate credentials
addAttachment()  : void
Add file attachment to email by absolute file path
clearAttachments()  : void
Remove all file attachments from email
getAttachments()  : array<string|int, mixed>
Get list of all file attachments
getBcc()  : string
Get current blind carbon copy recipient addresses
getCc()  : string
Get current carbon copy recipient addresses
getFrom()  : string
Get current sender email address
getHtml()  : string
Get current HTML email body
getReplyTo()  : string
Get current Reply-To email address
getSubject()  : string
Get current email subject line
getText()  : string
Get current plain text email body
getTo()  : string
Get current primary recipient email address
reset()  : void
Reset all email properties and response data to default empty state
send()  : string
Send configured email through Mailgun API with comprehensive error handling
setBcc()  : string
Set blind carbon copy recipients with previous value return
setCc()  : string
Set carbon copy recipients with previous value return
setFrom()  : string
Set sender email address with previous value return
setHtml()  : string
Set HTML email body with previous value return
setReplyTo()  : string
Set Reply-To email address with previous value return
setSubject()  : string
Set email subject line with previous value return
setText()  : string
Set plain text email body with previous value return
setTo()  : string
Set primary recipient email address with previous value return

Properties

$httpClientConfig

HTTP client configuration used for Mailgun API requests

public HttpClientConfig|null $httpClientConfig

Contains authentication, timeout, user agent, and verbose logging settings configured automatically during send() execution. Includes Mailgun API authentication and PrimordyxMailer user agent identification.

HTTP client settings or null before sending

Tags
since
1.0.0

$httpCode

HTTP status code from Mailgun API response

public int $httpCode = 0

Standard HTTP status codes indicating request result:

  • 200: Success - email queued for delivery
  • 400: Bad Request - invalid parameters or syntax
  • 401: Unauthorized - invalid API key or authentication failure
  • 429: Too Many Requests - rate limit exceeded
  • 500: Internal Server Error - Mailgun service issue

HTTP response status code (0 until send() called)

Tags
since
1.0.0

$httpResult

Complete HTTP response object from Mailgun API call

public HttpResult|null $httpResult

Contains the full HttpResult object after send() is called, providing access to response body, headers, CURL info, and detailed debugging information. Null until send() is executed.

HTTP response details or null before sending

Tags
since
1.0.0

$mailgun_id

Mailgun message ID returned after successful email sending

public string $mailgun_id = ''

Unique identifier assigned by Mailgun for successful email submissions. Used for tracking, webhooks, and API queries. Empty string until successful send. Format typically: random@domain.mailgun.org

Mailgun message identifier or empty string

Tags
since
1.0.0

$mailgun_message

Mailgun response message from API call

public string $mailgun_message = ''

Contains success confirmation or detailed error message from Mailgun API. For successful sends: "Queued. Thank you." For errors: Complete error details including validation failures.

Response message from Mailgun API

Tags
since
1.0.0

$attachments

private array<string|int, mixed> $attachments = []

List of file paths to attach

$suffix

private string $suffix

usually '/messages' but it could change over time I suppose

Methods

__construct()

Initialize MailgunMailer with API configuration and validate credentials

public __construct([string $endpoint = '' ][, string $apiKey = '' ][, string $domain = '' ][, string $suffix = '' ]) : mixed

Creates new MailgunMailer instance with Mailgun API settings. Parameters override default configuration from Bundle::appConfig(). All configuration values are required either via parameters or application configuration.

Configuration Priority

  1. Constructor parameters (highest priority)
  2. Bundle::appConfig() INI file settings
  3. Exception thrown if any required setting missing

Required Configuration Keys (in INI file)

  • mailgun.endpoint: Mailgun API base URL
  • mailgun.api_key: Mailgun private API key
  • mailgun.domain: Mailgun verified sending domain
  • mailgun.suffix: API endpoint suffix (typically '/messages')
Parameters
$endpoint : string = ''

Optional Mailgun API endpoint override

$apiKey : string = ''

Optional Mailgun API key override

$domain : string = ''

Optional Mailgun domain override

$suffix : string = ''

Optional API suffix override (default '/messages')

Tags
throws
Exception

When required Mailgun configuration missing from parameters or INI

since
1.0.0
example

Using Default Configuration

// Uses all settings from Bundle::appConfig()
$mailer = new MailgunMailer();
example

Override Specific Settings

// Override domain for different environment
$mailer = new MailgunMailer('', '', 'staging.example.com');
example

Complete Override

$mailer = new MailgunMailer(
    'https://api.eu.mailgun.net/v3',
    'key-1234567890abcdef',
    'mail.example.com',
    '/messages'
);
see
Bundle::appConfig()

For configuration management

fires

MailgunMailer.config.missing When configuration incomplete

addAttachment()

Add file attachment to email by absolute file path

public addAttachment(string $filename) : void

Adds file to attachment list for inclusion in email. File must exist and be readable at send time or will be silently skipped. Supports any file type that Mailgun accepts. Multiple attachments supported.

File validation occurs during send() - invalid paths are logged but don't prevent email sending. Large attachments may impact send performance and recipient deliverability.

Parameters
$filename : string

Absolute path to file for attachment

Tags
since
1.0.0
example

Single Attachment

$mailer->addAttachment('/var/www/uploads/report.pdf');
example

Multiple Attachments

$mailer->addAttachment('/path/to/document.pdf');
$mailer->addAttachment('/path/to/image.png');
$mailer->addAttachment('/path/to/spreadsheet.xlsx');
see
getAttachments()

To retrieve attachment list

see
clearAttachments()

To remove all attachments

clearAttachments()

Remove all file attachments from email

public clearAttachments() : void

Clears the attachment list without affecting other email properties. Useful when reusing MailgunMailer instance for emails with different attachment requirements.

Tags
since
1.0.0
example

Clear Before New Email

$mailer->clearAttachments();
$mailer->addAttachment('/path/to/new/file.pdf');
see
addAttachment()

To add attachments

see
getAttachments()

To check current attachments

see
reset()

To clear all email data including attachments

getAttachments()

Get list of all file attachments

public getAttachments() : array<string|int, mixed>

Returns array of absolute file paths that will be attached to email. Paths are added via addAttachment() and cleared via clearAttachments() or reset().

Tags
since
1.0.0
example

Check Attachment Count

$attachments = $mailer->getAttachments();
echo "Email has " . count($attachments) . " attachments";
see
addAttachment()

To add file attachments

see
clearAttachments()

To remove all attachments

Return values
array<string|int, mixed>

List of absolute file paths for attachment

getBcc()

Get current blind carbon copy recipient addresses

public getBcc() : string
Tags
since
1.0.0
see
setBcc()

To modify BCC addresses

Return values
string

Current BCC addresses (comma-separated) or empty string if not set

getCc()

Get current carbon copy recipient addresses

public getCc() : string
Tags
since
1.0.0
see
setCc()

To modify CC addresses

Return values
string

Current CC addresses (comma-separated) or empty string if not set

getFrom()

Get current sender email address

public getFrom() : string
Tags
since
1.0.0
see
setFrom()

To modify sender address

Return values
string

Current from address or empty string if not set

getHtml()

Get current HTML email body

public getHtml() : string
Tags
since
1.0.0
see
setHtml()

To modify HTML content

Return values
string

Current HTML body or empty string if not set

getReplyTo()

Get current Reply-To email address

public getReplyTo() : string
Tags
since
1.0.0
see
setReplyTo()

To modify reply-to address

Return values
string

Current reply-to address or empty string if not set

getSubject()

Get current email subject line

public getSubject() : string
Tags
since
1.0.0
see
setSubject()

To modify subject line

Return values
string

Current subject or empty string if not set

getText()

Get current plain text email body

public getText() : string
Tags
since
1.0.0
see
setText()

To modify text content

Return values
string

Current text body or empty string if not set

getTo()

Get current primary recipient email address

public getTo() : string
Tags
since
1.0.0
see
setTo()

To modify recipient address

Return values
string

Current to address or empty string if not set

reset()

Reset all email properties and response data to default empty state

public reset() : void

Clears all email composition data (recipients, subject, content, attachments) and response tracking information to prepare instance for reuse. Does not affect Mailgun configuration (endpoint, API key, domain, suffix).

Useful for sending multiple different emails with the same MailgunMailer instance without creating new objects or carrying over previous email data.

Tags
since
1.0.0
example

Reusing Mailer Instance

$mailer = new MailgunMailer();
// Send first email
$mailer->setFrom('sender@example.com')->setTo('user1@example.com');
$mailer->send();

// Reset and send different email
$mailer->reset();
$mailer->setFrom('sender@example.com')->setTo('user2@example.com');
$mailer->send();

send()

Send configured email through Mailgun API with comprehensive error handling

public send([bool $verboseLogging = false ]) : string

Transmits email using current instance configuration and attachment list to Mailgun. Handles authentication, file uploads, response processing, and EventManager integration for logging and debugging.

Sending Process

  1. Builds multipart form payload with email data and attachments
  2. Configures HTTP client with Mailgun authentication
  3. Posts to Mailgun API endpoint
  4. Processes response and updates instance properties
  5. Fires EventManager events for logging and monitoring

Response Handling

Updates instance properties with complete response information:

  • $httpCode: HTTP status code (200=success, 400/401/429/500=error)
  • $mailgun_id: Unique message ID for successful sends
  • $mailgun_message: Success confirmation or detailed error message
  • $httpResult: Complete HttpResult object for detailed analysis

Error Conditions

  • 400 Bad Request: Invalid parameters, missing required fields, malformed data
  • 401 Unauthorized: Invalid API key, domain not verified, authentication failure
  • 429 Too Many Requests: Rate limit exceeded, need to slow down sending
  • 500 Internal Server Error: Mailgun service issue, retry may succeed

File Attachment Processing

Files are validated for existence before attachment. Missing files are silently skipped to prevent send failure. Large files may impact performance and deliverability.

Parameters
$verboseLogging : bool = false

Enable detailed HTTP logging for debugging

Tags
since
1.0.0
example

Basic Send

$mailer->setFrom('sender@example.com')
       ->setTo('recipient@example.com')
       ->setSubject('Test')
       ->setText('Hello World!');
$messageId = $mailer->send();
if (!empty($messageId)) {
    echo "Email sent successfully: {$messageId}";
} else {
    echo "Send failed: {$mailer->mailgun_message}";
}
example

Send with Verbose Logging

$messageId = $mailer->send(true); // Enable detailed HTTP logging
echo "HTTP Status: {$mailer->httpCode}";
echo "Response: {$mailer->mailgun_message}";
example

Error Handling

$messageId = $mailer->send();
switch ($mailer->httpCode) {
    case 200:
        echo "Success! Message ID: {$messageId}";
        break;
    case 400:
        echo "Bad request: {$mailer->mailgun_message}";
        break;
    case 401:
        echo "Authentication failed - check API key";
        break;
    case 429:
        echo "Rate limited - slow down sending";
        break;
    default:
        echo "Unknown error: {$mailer->mailgun_message}";
}
fires

MailgunMailer.httpResult Complete HTTP response data for analysis

fires

MailgunMailer.200 Successful send with message ID and confirmation

fires

MailgunMailer.400 Bad request with error details

fires

MailgunMailer.401 Authentication failure details

fires

MailgunMailer.429 Rate limit exceeded notification

fires

MailgunMailer.500 Server error details

see
HttpClient::post()

For underlying HTTP request handling

see
EventManager::fire()

For event-driven logging integration

Return values
string

Mailgun message ID on success, empty string on failure

setBcc()

Set blind carbon copy recipients with previous value return

public setBcc([string $bcc = '' ]) : string

Configures BCC header for hidden secondary recipients. Accepts comma-separated list of email addresses. BCC recipients are hidden from all other recipients and receive exact copy of the email.

Parameters
$bcc : string = ''

Comma-separated list of BCC email addresses (empty to clear)

Tags
since
1.0.0
example

Single BCC Recipient

$previous = $mailer->setBcc('archive@example.com');
example

Multiple BCC Recipients

$mailer->setBcc('archive@example.com,compliance@example.com');
see
getBcc()

To retrieve current BCC addresses

see
setCc()

For visible recipients

Return values
string

Previous BCC addresses value

setCc()

Set carbon copy recipients with previous value return

public setCc([string $cc = '' ]) : string

Configures CC header for visible secondary recipients. Accepts comma-separated list of email addresses. All CC recipients will see each other's addresses and the primary recipient address.

Parameters
$cc : string = ''

Comma-separated list of CC email addresses (empty to clear)

Tags
since
1.0.0
example

Single CC Recipient

$previous = $mailer->setCc('manager@example.com');
example

Multiple CC Recipients

$mailer->setCc('manager@example.com,backup@example.com');
see
getCc()

To retrieve current CC addresses

see
setBcc()

For hidden recipients

Return values
string

Previous CC addresses value

setFrom()

Set sender email address with previous value return

public setFrom([string $from = '' ]) : string

Configures the From header for outgoing email. Must be from verified Mailgun domain or will result in sending failure. Supports both simple email address and formatted "Name email@domain.com" syntax.

Parameters
$from : string = ''

Sender email address (empty string to clear)

Tags
since
1.0.0
example

Simple Email Address

$previous = $mailer->setFrom('noreply@example.com');
example

Formatted Sender Name

$mailer->setFrom('Support Team <support@example.com>');
see
getFrom()

To retrieve current from address

Return values
string

Previous from address value

setHtml()

Set HTML email body with previous value return

public setHtml([string $html = '' ]) : string

Configures HTML version of email content. Supports full HTML including CSS styling, images, and links. Should be accompanied by plain text version for better compatibility and deliverability.

Parameters
$html : string = ''

HTML email body (empty string to clear)

Tags
since
1.0.0
example

Simple HTML Email

$previous = $mailer->setHtml('<h1>Welcome!</h1><p>Thank you for joining.</p>');
example

Complex HTML with Styling

$html = '<html><body style="font-family: Arial;">'
      . '<h2 style="color: #333;">Order Confirmation</h2>'
      . '<p>Your order has been processed successfully.</p>'
      . '</body></html>';
$mailer->setHtml($html);
see
getHtml()

To retrieve current HTML body

see
setText()

For plain text content

Return values
string

Previous HTML body value

setReplyTo()

Set Reply-To email address with previous value return

public setReplyTo([string $replyTo = '' ]) : string

Configures Reply-To header to override default reply behavior. When recipients reply to the email, responses will go to this address instead of the From address. Useful for no-reply senders that want responses directed to support addresses.

Parameters
$replyTo : string = ''

Reply-to email address (empty string to clear)

Tags
since
1.0.0
example

Support Reply Address

$mailer->setFrom('noreply@example.com');
$previous = $mailer->setReplyTo('support@example.com');
example

Same as From Address

$mailer->setFrom('sales@example.com');
$mailer->setReplyTo('sales@example.com'); // Explicit same address
see
getReplyTo()

To retrieve current reply-to address

Return values
string

Previous reply-to address value

setSubject()

Set email subject line with previous value return

public setSubject([string $subject = '' ]) : string

Configures the Subject header for email. Supports Unicode characters and standard email subject formatting. Empty subject will result in blank subject line (not recommended for deliverability).

Parameters
$subject : string = ''

Email subject line (empty string to clear)

Tags
since
1.0.0
example

Standard Subject

$previous = $mailer->setSubject('Monthly Newsletter - January 2025');
example

Unicode Subject

$mailer->setSubject('Confirmación de Pedido #12345');
see
getSubject()

To retrieve current subject

Return values
string

Previous subject value

setText()

Set plain text email body with previous value return

public setText([string $text = '' ]) : string

Configures plain text version of email content. Used as fallback for email clients that don't support HTML, and required by many spam filters even when HTML version is provided.

Parameters
$text : string = ''

Plain text email body (empty string to clear)

Tags
since
1.0.0
example

Simple Text Email

$previous = $mailer->setText('Hello, this is a plain text email.');
example

Multi-line Text Content

$content = "Dear Customer,\n\nThank you for your order.\n\nBest regards,\nSupport Team";
$mailer->setText($content);
see
getText()

To retrieve current text body

see
setHtml()

For HTML email content

Return values
string

Previous text body value

setTo()

Set primary recipient email address with previous value return

public setTo([string $to = '' ]) : string

Configures the To header for email delivery. Single email address only - for multiple primary recipients, use comma-separated format or multiple calls to this method.

Parameters
$to : string = ''

Primary recipient email address (empty string to clear)

Tags
since
1.0.0
example

Single Recipient

$previous = $mailer->setTo('user@example.com');
example

Multiple Recipients (Alternative)

$mailer->setTo('user1@example.com,user2@example.com');
see
getTo()

To retrieve current to address

see
setCc()

For carbon copy recipients

see
setBcc()

For blind carbon copy recipients

Return values
string

Previous to address value


        
On this page

Search results