FastSitePHP\Net\SmtpClient

SMTP Client

This class provides a simple API for communicating with SMTP Servers to send emails. Emails are created from the [FastSitePHP\Net\Email] class and this class has no dependencies other than the [Email] class.

This class implements Simple Mail Transfer Protocol as defined in RFC 5321 and various extensions including:
    AUTH        RFC 2554
    STARTTLS    RFC 3207
    SMTPUTF8    RFC 6531

Supported Verbs:
    EHLO    HELO    STARTTLS    AUTH    MAIL    RCPT
    VRFY    RSET    NOOP        DATA    HELP    QUIT

Supported Auth Methods:
    LOGIN    PLAIN

Código Fonte

GitHub

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($host = null, $port = null, $timeout = 5, \Closure $debug_callback = null)

Class Constructor Optionally connect to SMTP Server and define a Debug Callback. This is the recommended method for connecting to an SMTP Server because it automatically handles SMTP EHLO and STARTTLS commands.

Defaults to a 5 second timeout. Generally, communication with SMTP Servers is very fast and if a page were to freeze for many seconds a User may be likely to try and refresh it so a quick timeout of 5 seconds is used. The timeout applies both to the initial connection to the server and when reading of each reply.

[debug_callback] includes all send and reply text which can include the authentication password and private emails. When used with Authentication or emails it should only be used for debugging purposes.

__destruct()

Class Destructor Automatically send a QUIT command to the server and close the socket connection.

sendEmails(array $emails)

Função Estática

Static helper function that sends emails using config values defined in either the [app->config] array or as environment variables.

For sites that store sensitive information in the environment or special config files using this function prevents the need to hard-code SMTP and Auth values in the source. At a minimum values for [SMTP_HOST] and [SMTP_PORT] are required. [SMTP_TIMEOUT] defaults to 5 seconds if not set; [SMTP_USER] and [SMTP_PASSWORD] are only needed if you SMTP Server requires an Auth User.

send(Email $email)

Send an email

connect($host, $port, $timeout = 5)

Connect to the SMTP Server, see comments in the Class Constructor because that is the main method of connecting to an SMTP Server.

close()

Close SMTP Server Connection. If calling this manually then [quit()] should be called first.

ehlo($client = null)

Send an EHLO (Extended Hello) Command to the SMTP Server and read the reply lines which define supported extensions. This must be called after connecting to the server and also after sending STARTTLS.

Retorna: array - Reply lines from the server

helo($client = null)

Send a HELO (Hello) Command to the SMTP Server. This is typically used by very old servers that do not support EHLO.

Retorna: array - Reply lines from the server

fqdn()

Return the default FQDN 'fully-qualified domain name' used with Extended HELLO (EHLO) or HELLO (HELO) commands.

If the server name can be determined and it's part of a domain then the return value will be in the fromat of [server.example.com]. Other return values include the Web Server Host, or Server IP Address.

A send/reply example if this function returns [server.example.com] and connects to [smtp.gmail.com] from public IP [54.231.17.108]:
  send: EHLO server.example.com
  reply: 250-smtp.gmail.com at your service, [54.231.17.108]

Per RFC 5321 and 2821, Section [4.1.1.1] a FQDN is sent if available and if not then an IP Address is sent.

Per RFC 5321 and 2821, Section [4.1.4] the domain element is used by the server for logging purposes only and it does not decide to route an email based on this value.

Retorna: string

startTls($client = null)

Send a STARTTLS (Start Transport Layer Security) Command to the SMTP Server and once returned send a new EHLO Command.

This gets called by default when using Port 587.

When using PHP 5.6 or greater [TLS 1.2], [TLS 1.1], and [TLS 1.0] are supported and when using PHP 5.5 or below only [TLS 1.0] is supported.

Retorna: array - Reply lines from the server from the EHLO command

auth($user, $password)

Authenticate using the AUTH Command an a supported Auth method of either [AUTH LOGIN] or [AUTH PLAIN]. The method to call is determined based on the server's response.

Supported Auth Methods will come back from the EHLO command, examples:
  Gmail:
    250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
  AWS:
    reply: 250-AUTH PLAIN LOGIN

authLogin($user, $password)

Submit AUTH LOGIN credentials to the SMTP Server. This will typically be done over Secure Port 587.

authPlain($user, $password)

Submit AUTH PLAIN credentials to the SMTP Server. This will typically be done over Secure Port 587.

mailFrom($email, $utf8 = false)

Send the MAIL FROM Command to the SMTP Server and optionally include SMTPUTF8 if Unicode Emails Addresses are needed. This gets called once for the [From] Email Address. This is handled automatically from the [send()] function.

rcptTo($email)

Send the RCPT TO Command to the SMTP Server. This gets called for each person the email is being sent to. This is handled automatically from the [send()] function.

vrfy($email)

Send a VRFY (Verify) Command with an Email Address to the Server. This is an older SMTP Command that is usually ignored by servers since spammers could use it to check for existance of an email.

Retorna: array - Reply lines from the server

rset()

Send a RSET (Reset) Command to the SMTP Server. This would be used to cancel an message.

noop()

Send a NOOP (No operation) Command to the SMTP Server. This can be used to verify if the connection is ok.

data($data)

Send email message using the DATA command. This is handled automatically from the [send()] function.

help()

Send the HELP Command to the SMTP Server and return the rely lines.

Example return values:
  From Exchange:
    214-This server supports the following commands:
    214 HELO EHLO STARTTLS RCPT DATA RSET MAIL QUIT HELP AUTH BDAT
  From Gmail:
    214 2.0.0  https://www.google.com/search?btnI&q=RFC+5321 {{random_id}} - gsmtp

Retorna: array

quit()

Send a QUIT Command to the SMTP Server. This gets call automatically when the object instance is destroyed.

supports($extension)

Return true/false if an extension is supported based on the Server's response from the EHLO command.

This does not handle the size attribute, instead use the [size()] function.

Example:
  $smtp->supports('SMTPUTF8') Returns [true]
  if the EHLO response contains either '250-SMTPUTF8' or '250 SMTPUTF8'

Retorna: bool

size()

Returns the maximum allowed message size in bytes based on the Server's response from the EHLO command.

Returns -1 if [SIZE] was not specified from the server

Retorna: int