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.
<?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.
$settings['mail'] = array(
'transport' => 'smtp',
'host' => 'smtp.example.com',
'port' => 587,
'encryption' => 'tls',
'username' => 'user@example.com',
);
'FEGG_SMTP_PASSWORD' => '...',
| Key | Default | Remarks |
|---|---|---|
transport | 'sendmail' | 'smtp' to use SMTP |
host | 'localhost' | SMTP server. FEGG_SMTP_HOST in env.php overrides it |
port | 587 | Port |
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.
The PHPMailer instance is available as $mail->_mailer when you need a setting this wrapper does not cover.
Methods
Mail::__construct
Create a new email
Mail::subject
Set mail subject
Mail::body
Set mail body
Mail::pushHeader
Add custom header
Mail::removeHeader
Remove custom header
Mail::setReplyTo
Add a Reply-To address
Mail::clearReplyTo
Remove all Reply-To addresses
Mail::pushAttached
Add attachment file
Mail::send
Send email
Mail::log
Append a message to the log file
Mail::setDebugFlag
Set debug flag and log file name