Sending Email

Learn how to use Kirby's Email class to send emails with PHP's mail function, Amazon SES, Postmark, Mailgun or your own adaptor

PHP mail()

$email = new Email(array(
  'to'      => 'mail@example.com',
  'from'    => 'john@doe.com',
  'subject' => 'Yay, Kirby sends mails',
  'body'    => 'Hey, this is a test email!'
));

if($email->send()) {
  echo 'The email has been sent';
} else {
  echo $email->error()->message();
}

Amazon SES

http://aws.amazon.com/ses

$email = new Email(array(
  'to'      => 'mail@example.com',
  'from'    => 'john@doe.com',
  'subject' => 'Yay, Kirby sends mails',
  'body'    => 'Hey, this is a test email!', 
  'service' => 'amazon',
  'options' => array(
    'key'    => 'Your Amazon API Key',
    'secret' => 'Your Amazon API Secret',
    'host'   => 'email.us-east-1.amazonaws.com' // optional (default value)
  )
));

if($email->send()) {
  echo 'The email has been sent via Amazon SES';
} else {
  echo $email->error()->message();
}

Postmark

http://postmarkapp.com

$email = new Email(array(
  'to'      => 'mail@example.com',
  'from'    => 'john@doe.com',
  'subject' => 'Yay, Kirby sends mails',
  'body'    => 'Hey, this is a test email!', 
  'service' => 'postmark',
  'options' => array(
    'key' => 'Your Postmark API Key',
  )
));

if($email->send()) {
  echo 'The email has been sent via Postmark';
} else {
  echo $email->error()->message();
}

Mailgun

http://mailgun.com

$email = new Email(array(
  'to'      => 'mail@example.com',
  'from'    => 'john@doe.com',
  'subject' => 'Yay, Kirby sends mails',
  'body'    => 'Hey, this is a test email!', 
  'service' => 'mailgun',
  'options' => array(
    'key'    => 'Your Mailgun API Key',
    'domain' => 'Your Mailgun Domain'
  )
));

if($email->send()) {
  echo 'The email has been sent via Mailgun';
} else {
  echo $email->error()->message();
}

Global configuration

You can set up your email class once with global options and then overwrite the basics only when sending an email:

$email = new Email(array(
  'from'    => 'mail@example.com',
  'service' => 'postmark', 
  'options' => array(
    'key' => 'Your Postmark API key'
  )
));

// later in your app
foreach($listOfRecipients as $recipient) {

  $email->send(array(
    'to'      => $recipient,
    'subject' => 'Your personal email',
    'body'    => 'Hey! This is just for you'
  ));

}

How to write your own adaptor

A service adaptor is a simple callback function added to the $services array of the email class:

email::$services['yourservice'] = function($email) {
  // your adaptor code goes here.
};

Error handling in adaptors is super simple. Just throw a new Error like this: (An Error is an extended Exception)

email::$services['yourservice'] = function($email) {

  …
  // something went wrong
  throw new Error('Uh oh, that was not intended');
  …

};

API Docs

Check out the API docs for the Email class to learn more.