班级清单
- 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\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
源代码
相关链接
- https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol
- http://www.samlogic.net/articles/smtp-commands-reference.htm
- https://aws.amazon.com/blogs/messaging-and-targeting/debugging-smtp-conversations-part-1-how-to-speak-smtp/
- https://docs.microsoft.com/en-us/exchange/mail-flow/test-smtp-with-telnet?view=exchserver-2019
- https://tools.ietf.org/html/rfc5321
示例代码
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 on 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 not 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]);
*/
方法
__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)
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.
返回类型: 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.
返回类型: 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.
返回类型: 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.
返回类型: array
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.
返回类型: 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
返回类型: 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'
返回类型: 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
返回类型: int