Lista de Classes
- App\Middleware\Cors
- App\Middleware\Auth
- App\Middleware\Env
- AppMin
- Application
- Route
- Data\Database
- Data\Db2Database
- Data\OdbcDatabase
- Data\Validator
- Data\KeyValue\SqliteStorage
- Data\Log\FileLogger
- Data\Log\HtmlLogger
- Encoding\Base64Url
- Encoding\Json
- Encoding\Utf8
- Environment\DotEnv
- Environment\System
- FileSystem\Search
- FileSystem\Security
- FileSystem\Sync
- Lang\I18N
- Lang\L10N
- Lang\Time
- Media\Image
- Net\Config
- Net\Email
- Net\HttpClient
- Net\HttpResponse
- Net\IP
- Net\SmtpClient
- Security\Crypto
- Security\Password
- Security\Crypto\Encryption
- Security\Crypto\FileEncryption
- Security\Crypto\JWT
- Security\Crypto\PublicKey
- Security\Crypto\Random
- Security\Crypto\SignedData
- Security\Web\CsrfSession
- Security\Web\CsrfStateless
- Security\Web\RateLimit
- Web\Request
- Web\Response
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.
Código Fonte
Links Relacionados
Código de Exemplo
Envia um E-mail via um Servidor SMTP
// Defina as Configurações de E-mail
$from = 'noreply@example.com';
$to = 'user.name@example.com';
$subject = 'E-mail de Teste de FastSitePHP em ' . date(DATE_RFC2822);
$body = '<h1>Título do E-mail</h1><p style="color:blue;">Isto é um teste.</p>';
// Cria um Objeto E-mail
$email = new \FastSitePHP\Net\Email($from, $to, $subject, $body);
// A Classe Email também tem várias definições adicionais e pode ser criada
// sem especificar quaisquer parâmetros. Ao definir os endereços de e-mail
// de [From] ou [Reply-To], um os seguintes formatos pode ser utilizado:
// String: 'Email Address'
// Array: ['Email', 'Name']
// E quando especificar para quem enviar o e-mail para qualquer um dos
// formatos, pode utilizar:
// String 'Endereço de E-mail'
// Array: ['E-mail', 'Nome']
// Array: ['Endereço de E-mail 1', 'Endereço de E-mail 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');
*/
// Arquivos anexos também são suportados:
//
// $email->attachFile($file_path);
// Servidores SMTP que suportam E-mails Unicode pode utilizar
// [allowUnicodeEmails(true)]. Quando utilizado, O Cliente SMTP envia uma
// opção SMTPUTF8 se o servidor suportá-la.
//
// $email->allowUnicodeEmails(true)->from('无回复@example.com');
// Configurações SMTP
$host = 'smtp.example.com';
$port = 25;
$auth_user = null;
$auth_pass = null;
// Cria Cliente SMTP e Envia E-mail.
// Uma vez que a variável para o Client SMTP não estiver mais em uso ou
// definida como null, então, um comando 'QUIT' é automaticamente enviado
// para o Servidor SMTP e a conexão é fechada.
$smtp = new \FastSitePHP\Net\SmtpClient($host, $port);
if ($auth_user !== null) {
$smtp->auth($auth_user, $auth_pass);
}
$smtp->send($email);
$smtp = null;
// Opções adicionais podem ser especificadas, em segundos, para timeout e
// para logging
$timeout = 2;
$debug_callback = function($message) {
echo '[' . date('H:i:s') . '] ' . trim($message) . "\n";
};
// A Classe [SmtpClient] também suporta uma API de fácil utilização para
// comunicar com Servidores SMTP. Neste exemplo Gmail é utilizado e diversos
// comandos são realizados. Mensagens são logadas para a função
// [$debug_callback].
$host = 'smtp.gmail.com';
$port = 587;
$smtp2 = new \FastSitePHP\Net\SmtpClient($host, $port, $timeout, $debug_callback);
$smtp2->help();
$smtp2->noop();
$smtp2->quit();
$smtp2->close();
// Um ou mais e-mails pode também ser enviados utilizando Valores de
// Configuração de App ou Variáveis de Ambiente do Sistema. Este tipo de
// configuração pode ser utilizada para prevenir que dados de autenticação
// sensíveis sejam salvos com o código lógico principal.
/*
$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]);
*/
Métodos
__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)
Get or set the [From] Email Address, this function accepts a string with an Email address or an array with ['Email', 'Name'].
Retorna: null | string | $this
replyTo($new_value = null)
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.
Retorna: null | string | $this
to($new_value = null)
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']
Retorna: array | $this
cc($new_value = null)
Get or set [CC] Email Addresses. This function uses the same format as the [to()] function.
Retorna: array | $this
bcc($new_value = null)
Get or set [BCC] Email Addresses. This function uses the same format as the [to()] function.
Retorna: array | $this
subject($new_value = null)
Get or set the Subject of the email.
Retorna: null | string | $this
body($new_value = null)
Get or set the Body of the email.
Retorna: null | string | $this
isHtml($new_value = null)
Get or set the type of email to send:
HTML = true (Default)
Text = false
Retorna: bool | $this
priority($new_value = null)
Sends both [X-Priority] and [Importance] headers. When setting specify one of ['High', 'Normal', or 'Low'].
Retorna: null | string | $this
header($name, $new_value = null)
Get or set a Custom Email Header
Retorna: $this | null | string
safeHeaderNames($new_value = null)
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.
Retorna: 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.
Retorna: $this
allowUnicodeEmails($new_value = null)
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.
Retorna: bool | $this
encodeFileNames($new_value = null)
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.
Retorna: bool | $this
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
- https://tools.ietf.org/html/rfc5987
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.
Retorna: string