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
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
$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
$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
$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
$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
$apiKey
private
string
$apiKey
Mailgun API key
$attachments
private
array<string|int, mixed>
$attachments
= []
List of file paths to attach
$bcc
private
string
$bcc
= ''
BCC addresses
$cc
private
string
$cc
= ''
CC addresses
$domain
private
string
$domain
Mailgun domain name
$endpoint
private
string
$endpoint
Mailgun base endpoint
$from
private
string
$from
= ''
Sender email address
$html
private
string
$html
= ''
HTML email body
$replyTo
private
string
$replyTo
= ''
Reply-To address
$subject
private
string
$subject
= ''
Email subject line
$suffix
private
string
$suffix
usually '/messages' but it could change over time I suppose
$text
private
string
$text
= ''
Plain text email body
$to
private
string
$to
= ''
Recipient email address
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
- Constructor parameters (highest priority)
- Bundle::appConfig() INI file settings
- 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
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
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
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
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
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
Return values
string —Current CC addresses (comma-separated) or empty string if not set
getFrom()
Get current sender email address
public
getFrom() : string
Tags
Return values
string —Current from address or empty string if not set
getHtml()
Get current HTML email body
public
getHtml() : string
Tags
Return values
string —Current HTML body or empty string if not set
getReplyTo()
Get current Reply-To email address
public
getReplyTo() : string
Tags
Return values
string —Current reply-to address or empty string if not set
getSubject()
Get current email subject line
public
getSubject() : string
Tags
Return values
string —Current subject or empty string if not set
getText()
Get current plain text email body
public
getText() : string
Tags
Return values
string —Current text body or empty string if not set
getTo()
Get current primary recipient email address
public
getTo() : string
Tags
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
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
- Builds multipart form payload with email data and attachments
- Configures HTTP client with Mailgun authentication
- Posts to Mailgun API endpoint
- Processes response and updates instance properties
- 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
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
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
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
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
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
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
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
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
Return values
string —Previous to address value