Sending Emails with Mailgun

The Mailgun API is built on HTTP and is RESTful. It uses predictable, resource- oriented URLs and built-in HTTP capabilities for passing parameters and authentication. The Mailgun API responds with standard HTTP response codes to indicate errors, and returns JSON.

Mailgun has published libraries for various languages. You can use these libraries or your favorite HTTP/REST library to make HTTP calls to Mailgun.

For more code samples in other programming languages, see Mailgun's documentation.

Pricing

As a Google Cloud Platform user, your first 30,000 messages are free every month. See the monthly pricing calculator on the sign up page for pricing on additional messages and volume discounts.

Setup

  • The mailgun-php library provides an interface to easily interact with the Mailgun API. To use the library:

  • Add the Mailgun package and an HTTP client to your composer.json file. This example uses Guzzle 6:

    composer require mailgun/mailgun-php php-http/guzzle6-adapter
    
  • Include Composer's autoloader.

Examples

Sending a plain text message:

// Instantiate the client.
$httpClient = new Http\Adapter\Guzzle6\Client();
$mailgunClient = new Mailgun\Mailgun($mailgunApiKey, $httpClient);

// Make the call to the client.
$result = $mailgunClient->sendMessage($mailgunDomain, array(
    'from' => sprintf('Example Sender <mailgun@%s>', $mailgunDomain),
    'to' => $recipient,
    'subject' => 'Hello',
    'text' => 'Testing some Mailgun awesomeness!',
));

Sending a message with HTML and text parts. This example also attaches files to the message:

// Instantiate the client.
$httpClient = new Http\Adapter\Guzzle6\Client();
$mailgunClient = new Mailgun\Mailgun($mailgunApiKey, $httpClient);
$fileAttachment = __DIR__ . '/attachment.txt';

// Make the call to the client.
$result = $mailgunClient->sendMessage($mailgunDomain, array(
    'from' => sprintf('Example Sender <mailgun@%s>', $mailgunDomain),
    'to' => $recipient,
    'cc' => $cc,
    'bcc' => $bcc,
    'subject' => 'Hello',
    'text' => 'Testing some Mailgun awesomeness!',
    'html' => '<html>HTML version of the body</html>',
), array(
    'attachment' => array($fileAttachment, $fileAttachment),
));

Sample response:

{
    "message": "Queued. Thank you.",
    "id": "<20111114174239.25659.5817@samples.mailgun.org>"
}

Learning more

For more detailed examples and information, including how to track and route messages, see Mailgun's documentation.

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...

App Engine flexible environment for PHP docs