FastSitePHP\Net\Email

Email Message API

This classes is used for sending emails along with the [SmtpClient] class. See docs in [SmtpClient] for more.

In general this classes provides getter/setter functions for common email fields and the format of email addresses and header fields are validated when set. Unicode Email Addresses are supported when [allowUnicodeEmails(true)] is called.

Source Code

GitHub

Example Code

Send an Email through an SMTP Server

// Define Email Settings
$from = 'noreply@example.com';
$to = 'user.name@example.com';
$subject = 'Email Test from FastSitePHP at ' . date(DATE_RFC2822);
$body = '<h1>Email Title</h1><p style="color:blue;">This is a test.</p>';

// Create an Email Object
$email = new \FastSitePHP\Net\Email($from, $to, $subject, $body);

// The Email Class also has many additional settings and can be created
// without specifying any parameters. When setting [From] or [Reply-To]
// email addresses one of the following formats can be used:
//   String: 'Email Address'
//   Array: ['Email', 'Name']
// And when specifying who to send email to any of the formats can be used:
//   String 'Email Address'
//   Array: ['Email', 'Name']
//   Array: ['Email Address 1', 'Email Address 2', '...']
/*
$email = new \FastSitePHP\Net\Email();
$email
    ->from(['noreply@example.com', 'No Reply'])
    ->replyTo('test@example.com')
    ->to(['email1@example.com', 'email2@example.com'])
    ->cc('email3@example.com')
    ->bcc('email4@example.com')
    ->priority('High')
    ->header('X-Transaction-ID', '123abc');
*/

// File attachements are also supported:
//
// $email->attachFile($file_path);

// SMTP Servers that support Unicode Emails can use [allowUnicodeEmails(true)].
// When used the SMTP Client sends a SMTPUTF8 option if the server supports it.
//
// $email->allowUnicodeEmails(true)->from('无回复@example.com');

// SMTP Settings
$host = 'smtp.example.com';
$port = 25;
$auth_user = null;
$auth_pass = null;

// Create SMTP Client and Send Email.
// Once the variable for the SMTP Client is no longer used or set to null
// then it automatically sends a 'QUIT' command to the SMTP Server and closes
// the connection.
$smtp = new \FastSitePHP\Net\SmtpClient($host, $port);
if ($auth_user !== null) {
    $smtp->auth($auth_user, $auth_pass);
}
$smtp->send($email);
$smtp = null;

// Additional options can be specified for timeout (in seconds) and for logging
$timeout = 2;
$debug_callback = function($message) {
    echo '[' . date('H:i:s') . '] ' . trim($message) . "\n";
};

// The [SmtpClient] Class also supports an easy to use API for communicating
// with SMTP Servers. In this example Gmail is used and several commands are
// performed. Messages are logged to the [$debug_callback] function.
$host = 'smtp.gmail.com';
$port = 587;
$smtp2 = new \FastSitePHP\Net\SmtpClient($host, $port, $timeout, $debug_callback);
$smtp2->help();
$smtp2->noop();
$smtp2->quit();
$smtp2->close();

// One or more emails can also be sent using App Config Values or System
// Enviroment Variables. This type of setup can be used to prevent sensitive
// authentication info from being saved with the main code logic.
/*
$app->config['SMTP_HOST'] = $host;
$app->config['SMTP_PORT'] = $port;
$app->config['SMTP_TIMEOUT'] = $timeout;
$app->config['SMTP_USER'] = $auth_user;
$app->config['SMTP_PASSWORD'] = $auth_pass;

\FastSitePHP\Net\SmtpClient::sendEmails([$email]);
*/

Methods

__construct($from = null, $to = null, $subject = null, $body = null)

Class Constructor Key email fields can be defined when an object is created

from($new_value = null)

Getter / Setter Property

Get or set the [From] Email Address, this function accepts a string with an Email address or an array with ['Email', 'Name'].

Returns: null | string | $this

replyTo($new_value = null)

Getter / Setter Property

Get or set the [Reply-To] Email Address, this function accepts a string with an Email address or an array with ['Email', 'Name'].

[Reply-To] does not show by default when viewing an Email, however if a user clicks [Reply] then it appears. This is useful if you want to send the email from a no-reply email but still allow a user to reply.

Returns: null | string | $this

to($new_value = null)

Getter / Setter Property

Get or set [To] Email Addresses. This function can set one or many email addresses at the same time.

Accepted options:
    Null - Returns a list of Email Address Strings to Send to.
    Array of [Email Address Strings]
    'email address'
    Array with ['Email', 'Name']

Returns: array | $this

cc($new_value = null)

Getter / Setter Property

Get or set [CC] Email Addresses. This function uses the same format as the [to()] function.

Returns: array | $this

bcc($new_value = null)

Getter / Setter Property

Get or set [BCC] Email Addresses. This function uses the same format as the [to()] function.

Returns: array | $this

subject($new_value = null)

Getter / Setter Property

Get or set the Subject of the email.

Returns: null | string | $this

body($new_value = null)

Getter / Setter Property

Get or set the Body of the email.

Returns: null | string | $this

isHtml($new_value = null)

Getter / Setter Property

Get or set the type of email to send:
    HTML = true (Default)
    Text = false

Returns: bool | $this

priority($new_value = null)

Getter / Setter Property

Sends both [X-Priority] and [Importance] headers. When setting specify one of ['High', 'Normal', or 'Low'].

Returns: null | string | $this

header($name, $new_value = null)

Getter / Setter Property

Get or set a Custom Email Header

Returns: $this | null | string

safeHeaderNames($new_value = null)

Getter / Setter Property

By default only characters [A-Z], [a-z], [0-9], and [-] are allowed for Custom Header Field Names when using the [header()] function. Setting this value to false will allow any character other than New-Lines (CR, LF), Null (char 0), and [:] to be used.

Returns: bool | $this

attachFile($file_path)

Add a file attachment to the email.

IMPORTANT - File paths should generally not be passed as user parameters because a user could specify files other than the intended file. If an App does need to allow the user to specify a file then the code should be carefully reviewed and tested for security.

Typical usage of this feature would be having a script generate a report and then the report gets attached to an email sent to users on an automated schedule.

Returns: $this

allowUnicodeEmails($new_value = null)

Getter / Setter Property

Set to true to allow Unicode Emails to be sent. When the [SmtpClient] Class sends the email it checks this and if set to [true] sends the option SMTPUTF8 if supported by the SMTP Server.

Setting this value is only required if using Unicode Email Addresses and it is not required for sending content with Unicode characters (Subject, Body, Attachement File Names, Headers, etc).

This function defaults to false so that email address validation uses strict rules.

Returns: bool | $this

encodeFileNames($new_value = null)

Getter / Setter Property

Get or set whether attached file names should be UTF-8 encoded. Defaults to false.

If set to true then the following MIME Header:
  "Content-Disposition: attachment; filename*=UTF-8''{encoded_name}" is included in the email message. For modern SMTP Servers and widely used email providers this is generally not needed even when the file name includes Unicode Characters.

Returns: bool | $this

message()

Return the Email message as a String encoded as UTF-8 using Base64 for the [SmtpClient] to send with the DATA command. This function is public but generally only needs to be called internally by the [SmtpClient] Class.

Returns: string