Skip to content

Instantly share code, notes, and snippets.

@tmugford
Created September 14, 2018 11:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmugford/91b6a95f81a04f8c5c3c1306ea510862 to your computer and use it in GitHub Desktop.
Save tmugford/91b6a95f81a04f8c5c3c1306ea510862 to your computer and use it in GitHub Desktop.
Kirby custom SMTP email driver using PHPMailer (assumes SMTP authentication is required)

In the Kirby root

composer require phpmailer/phpmailer

Add autoload.php and smtp.php to /site/plugins, and add appropriate SMTP configuration options to the relevant config file (see included config.php as an example).

<?php
require kirby()->roots()->index() . DS . 'vendor' . DS . 'autoload.php';
<?php
c::set('email.service', 'smtp');
c::set('email.options', [
'host' => 'host',
'port' => 'port',
'user' => 'user',
'password' => 'password',
]);
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
email::$services['smtp'] = function($email) {
if(empty($email->options['host'])) throw new Error('Missing SMTP host');
if(empty($email->options['port'])) throw new Error('Missing SMTP port');
if(empty($email->options['user'])) throw new Error('Missing SMTP user');
if(empty($email->options['password'])) throw new Error('Missing SMTP password');
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = $email->options['host'];
$mail->Port = $email->options['port'];
$mail->SMTPAuth = true;
$mail->Username = $email->options['user'];
$mail->Password = $email->options['password'];
$mail->setFrom($email->from);
$mail->addAddress($email->to);
if (!empty($email->replyTo)) $mail->addReplyTo($email->replyTo);
if (!empty($email->cc)) $mail->addCC($email->cc);
if (!empty($email->bcc)) $mail->addBCC($email->bcc);
$mail->Subject = $email->subject;
$mail->Body = $email->body;
$mail->send();
} catch (Exception $e) {
throw new Error($mail->ErrorInfo);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment