Skip to main content
Version: Fegg 5.x (next)

Introduction

Providing some functions for sending email

Fegg\Tool\Mail is a wrapper of the bundled PHPMailer. Emails are sent as plain text, in UTF-8 with base64 encoding. By default they go through sendmail (the sendmail_path of php.ini is used when PHPMailer's default sendmail path does not exist); they can also be sent over SMTP.

How to use​

Import Fegg\Tool\Mail and create it with new. A failed send throws PHPMailer\PHPMailer\Exception, so wrap the sending in try / catch.

Controller
<?php
namespace Site\Controller;

defined('FEGG_CORE_DIR') || exit;

use Fegg\Tool\Mail;
use PHPMailer\PHPMailer\Exception;

class Contact extends Controller
{
public function post()
{
$body = $this->fetchPage('/contact/mail/to_admin');

try {
$mail = new Mail('Mail subject', $body);
$mail->send('admin@example.com', 'Sender name', 'from@example.com');
} catch (Exception $e) {
// Failed to send: $e->getMessage()
}
}
}

The contact form of the skeleton (htdocs/_fegg/site/controller/Contact.php) is a complete example, including Mail::setDebugFlag to write the emails to a log file instead of sending them.

SMTP​

To send through an SMTP server instead of sendmail, set $settings['mail'] in site/config/settings.php, and put the password in site/config/env.php (or an environment variable) as FEGG_SMTP_PASSWORD. Every Mail object then uses it, the contact form included.

htdocs/_fegg/site/config/settings.php
$settings['mail'] = array(
'transport' => 'smtp',
'host' => 'smtp.example.com',
'port' => 587,
'encryption' => 'tls',
'username' => 'user@example.com',
);
htdocs/_fegg/site/config/env.php
'FEGG_SMTP_PASSWORD' => '...',
KeyDefaultRemarks
transport'sendmail''smtp' to use SMTP
host'localhost'SMTP server. FEGG_SMTP_HOST in env.php overrides it
port587Port
encryption'tls''tls': STARTTLS. 'ssl': SMTPS (usually port 465). '': none
username''Login user; without it no authentication is used. FEGG_SMTP_USERNAME in env.php overrides it

The connection times out after 10 seconds. Never write the password in settings.php, which is committed.

note

The PHPMailer instance is available as $mail->_mailer when you need a setting this wrapper does not cover.

Methods​