CakePHP: Send transactional emails using Mailgun

Sending email is a basic need of every application. Examples of transactional emails are Receipts, Password Resets, Signup Confirmation Emails etc.

Why should we use transactional email service providers?

There is another options to send these type of emails – use email service providers. Now, the question is, why should we use transactional email service providers such as Mailgun or SparkPost or Mandrill?

  • Speed and Deliverability
  • Limitation of emails e.g. Gmail has limit to send daily email via SMTP
  • Higher probability of inbox penetration
  • Reports – different reports of your emails

In CakePHP, there is a in-built functionality to send emails using different options like SMTP or PHP’s mail library. See my article for more details.

After reviewing several transactional email service providers, I have selected Mailgun and created a plugin to easily integrate it with CakePHP. Now, let’s start with implementation.

Installation

Install the plugin into your CakePHP application using composer like,

After installing, load the plugin into your application like,

The basic installation is now completed. For more information on plugin installation, see the doc here.

Account setup & configuration

First, create your account at Mailgun. After signup, get your API key from account settings. You also need to setup your sending domain there as well. It is quite easy – see their doc here.

Now, we need to configure our CakePHP application to use Mailgun as email sending service. For that, set your Mailgun credentials in EmailTransport settings in app.php.

 

The above settings will be used in Mailgun API configuration. Once you setup the email transport, create a new email delivery profile. Open your app.php and under Email settings, set the following.

Now, our application is configured to use Mailgun as email sending service.

Send email

Sending email using above configuration is very easy. Just create your Email object as usual and pass mailgun as argument.

 

That is it. Now it will use Mailgun to send your emails. Let’s see some examples.

Send a simple email

Below is a very simple example of sending email.

Send email with custom headers

Mailgun supports additional parameters. You can set them using addHeaders() function. See here for list of additional parameters.

 

Send email with template and attachments

 

That is it. If you have a problem with this plugin or found any bug, please open an issue on GitHub.

You may also like...