SMTP
in package
PHPMailer RFC821 SMTP email transport class.
Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server.
Tags
Table of Contents
- DEBUG_CLIENT = 1
- Debug level to show client -> server messages.
- DEBUG_CONNECTION = 3
- Debug level to show connection status, client -> server and server -> client messages.
- DEBUG_LOWLEVEL = 4
- Debug level to show all messages.
- DEBUG_OFF = 0
- Debug level for no output.
- DEBUG_SERVER = 2
- Debug level to show client -> server and server -> client messages.
- DEFAULT_PORT = 25
- The SMTP port to use if one is not specified.
- LE = "\r\n"
- SMTP line break constant.
- MAX_LINE_LENGTH = 998
- The maximum line length allowed by RFC 5321 section 4.5.3.1.6, *excluding* a trailing CRLF break.
- MAX_REPLY_LENGTH = 512
- The maximum line length allowed for replies in RFC 5321 section 4.5.3.1.5, *including* a trailing CRLF line break.
- VERSION = '6.7.1'
- The PHPMailer SMTP version number.
- $Debugoutput : string|callable|LoggerInterface
- How to handle debug output.
- $do_debug : int
- Debug output level.
- $do_verp : bool
- Whether to use VERP.
- $Timelimit : int
- How long to wait for commands to complete, in seconds.
- $Timeout : int
- The timeout value for connection, in seconds.
- $error : array<string|int, mixed>
- Error information, if any, for the last SMTP command.
- $helo_rply : string|null
- The reply the server sent to us for HELO.
- $last_reply : string
- The most recent reply received from the server.
- $last_smtp_transaction_id : string|bool|null
- The last transaction ID issued in response to a DATA command, if one was detected.
- $server_caps : array<string|int, mixed>|null
- The set of SMTP extensions sent in reply to EHLO command.
- $smtp_conn : resource|null
- The socket for the server connection.
- $smtp_transaction_id_patterns : array<string|int, string>
- Patterns to extract an SMTP transaction id from reply to a DATA command.
- authenticate() : bool
- Perform SMTP authentication.
- client_send() : int|bool
- Send raw data to the server.
- close() : mixed
- Close the socket and clean up the state of the class.
- connect() : bool
- Connect to an SMTP server.
- connected() : bool
- Check connection state.
- data() : bool
- Send an SMTP DATA command.
- getDebugLevel() : int
- Get debug output level.
- getDebugOutput() : string
- Get debug output method.
- getError() : array<string|int, mixed>
- Get the latest error.
- getLastReply() : string
- Get the last reply from the server.
- getLastTransactionID() : bool|string|null
- Get the queue/transaction ID of the last SMTP transaction If no reply has been received yet, it will return null.
- getServerExt() : string|bool|null
- Get metadata about the SMTP server from its HELO/EHLO response.
- getServerExtList() : array<string|int, mixed>|null
- Get SMTP extensions available on the server.
- getTimeout() : int
- Get SMTP timeout.
- getVerp() : bool
- Get VERP address generation mode.
- hello() : bool
- Send an SMTP HELO or EHLO command.
- mail() : bool
- Send an SMTP MAIL command.
- noop() : bool
- Send an SMTP NOOP command.
- quit() : bool
- Send an SMTP QUIT command.
- recipient() : bool
- Send an SMTP RCPT command.
- reset() : bool
- Send an SMTP RSET command.
- sendAndMail() : bool
- Send an SMTP SAML command.
- setDebugLevel() : mixed
- Set debug output level.
- setDebugOutput() : mixed
- Set debug output method.
- setTimeout() : mixed
- Set SMTP timeout.
- setVerp() : mixed
- Enable or disable VERP address generation.
- startTLS() : bool
- Initiate a TLS (encrypted) session.
- turn() : bool
- Send an SMTP TURN command.
- verify() : bool
- Send an SMTP VRFY command.
- edebug() : mixed
- Output debugging info via a user-selected method.
- errorHandler() : mixed
- Reports an error number and string.
- get_lines() : string
- Read the SMTP server's response.
- getSMTPConnection() : false|resource
- Create connection to the SMTP server.
- hmac() : string
- Calculate an MD5 HMAC hash.
- parseHelloFields() : mixed
- Parse a reply to HELO/EHLO command to discover server extensions.
- recordLastTransactionID() : bool|string|null
- Extract and return the ID of the last SMTP transaction based on a list of patterns provided in SMTP::$smtp_transaction_id_patterns.
- sendCommand() : bool
- Send a command to an SMTP server and check its return code.
- sendHello() : bool
- Send an SMTP HELO or EHLO command.
- setError() : mixed
- Set error messages and codes.
Constants
DEBUG_CLIENT
Debug level to show client -> server messages.
public
int
DEBUG_CLIENT
= 1
DEBUG_CONNECTION
Debug level to show connection status, client -> server and server -> client messages.
public
int
DEBUG_CONNECTION
= 3
DEBUG_LOWLEVEL
Debug level to show all messages.
public
int
DEBUG_LOWLEVEL
= 4
DEBUG_OFF
Debug level for no output.
public
int
DEBUG_OFF
= 0
DEBUG_SERVER
Debug level to show client -> server and server -> client messages.
public
int
DEBUG_SERVER
= 2
DEFAULT_PORT
The SMTP port to use if one is not specified.
public
int
DEFAULT_PORT
= 25
LE
SMTP line break constant.
public
string
LE
= "\r\n"
MAX_LINE_LENGTH
The maximum line length allowed by RFC 5321 section 4.5.3.1.6, *excluding* a trailing CRLF break.
public
int
MAX_LINE_LENGTH
= 998
Tags
MAX_REPLY_LENGTH
The maximum line length allowed for replies in RFC 5321 section 4.5.3.1.5, *including* a trailing CRLF line break.
public
int
MAX_REPLY_LENGTH
= 512
Tags
VERSION
The PHPMailer SMTP version number.
public
string
VERSION
= '6.7.1'
Properties
$Debugoutput
How to handle debug output.
public
string|callable|LoggerInterface
$Debugoutput
= 'echo'
Options:
-
echo
Output plain-text as-is, appropriate for CLI -
html
Output escaped, line breaks converted to<br>
, appropriate for browser output -
error_log
Output to error log as configured in php.ini Alternatively, you can provide a callable expecting two params: a message string and the debug level:
$smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only debug
level output is used:
$mail->Debugoutput = new myPsr3Logger;
$do_debug
Debug output level.
public
int
$do_debug
= self::DEBUG_OFF
Options:
- self::DEBUG_OFF (
0
) No debug output, default - self::DEBUG_CLIENT (
1
) Client commands - self::DEBUG_SERVER (
2
) Client commands and server responses - self::DEBUG_CONNECTION (
3
) As DEBUG_SERVER plus connection status - self::DEBUG_LOWLEVEL (
4
) Low-level data output, all messages.
$do_verp
Whether to use VERP.
public
bool
$do_verp
= false
Tags
$Timelimit
How long to wait for commands to complete, in seconds.
public
int
$Timelimit
= 300
Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.
$Timeout
The timeout value for connection, in seconds.
public
int
$Timeout
= 300
Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2. This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure.
Tags
$error
Error information, if any, for the last SMTP command.
protected
array<string|int, mixed>
$error
= ['error' => '', 'detail' => '', 'smtp_code' => '', 'smtp_code_ex' => '']
$helo_rply
The reply the server sent to us for HELO.
protected
string|null
$helo_rply
If null, no HELO string has yet been received.
$last_reply
The most recent reply received from the server.
protected
string
$last_reply
= ''
$last_smtp_transaction_id
The last transaction ID issued in response to a DATA command, if one was detected.
protected
string|bool|null
$last_smtp_transaction_id
$server_caps
The set of SMTP extensions sent in reply to EHLO command.
protected
array<string|int, mixed>|null
$server_caps
Indexes of the array are extension names. Value at index 'HELO' or 'EHLO' (according to command that was sent) represents the server name. In case of HELO it is the only element of the array. Other values can be boolean TRUE or an array containing extension options. If null, no HELO/EHLO string has yet been received.
$smtp_conn
The socket for the server connection.
protected
resource|null
$smtp_conn
$smtp_transaction_id_patterns
Patterns to extract an SMTP transaction id from reply to a DATA command.
protected
array<string|int, string>
$smtp_transaction_id_patterns
= ['exim' => '/[\\d]{3} OK id=(.*)/', 'sendmail' => '/[\\d]{3} 2.0.0 (.*) Message/', 'postfix' => '/[\\d]{3} 2.0.0 Ok: queued as (.*)/', 'Microsoft_ESMTP' => '/[0-9]{3} 2.[\\d].0 (.*)@(?:.*) Queued mail for delivery/', 'Amazon_SES' => '/[\\d]{3} Ok (.*)/', 'SendGrid' => '/[\\d]{3} Ok: queued as (.*)/', 'CampaignMonitor' => '/[\\d]{3} 2.0.0 OK:([a-zA-Z\\d]{48})/', 'Haraka' => '/[\\d]{3} Message Queued \\((.*)\\)/', 'Mailjet' => '/[\\d]{3} OK queued as (.*)/']
The first capture group in each regex will be used as the ID. MS ESMTP returns the message ID, which may not be correct for internal tracking.
Methods
authenticate()
Perform SMTP authentication.
public
authenticate(string $username, string $password[, string $authtype = null ][, OAuthTokenProvider $OAuth = null ]) : bool
Must be run after hello().
Parameters
- $username : string
-
The user name
- $password : string
-
The password
- $authtype : string = null
-
The auth type (CRAM-MD5, PLAIN, LOGIN, XOAUTH2)
- $OAuth : OAuthTokenProvider = null
-
An optional OAuthTokenProvider instance for XOAUTH2 authentication
Tags
Return values
bool —True if successfully authenticated
client_send()
Send raw data to the server.
public
client_send(string $data[, string $command = '' ]) : int|bool
Parameters
- $data : string
-
The data to send
- $command : string = ''
-
Optionally, the command this is part of, used only for controlling debug output
Return values
int|bool —The number of bytes sent to the server or false on error
close()
Close the socket and clean up the state of the class.
public
close() : mixed
Don't use this function without first trying to use QUIT.
Tags
Return values
mixed —connect()
Connect to an SMTP server.
public
connect(string $host[, int $port = null ][, int $timeout = 30 ][, array<string|int, mixed> $options = [] ]) : bool
Parameters
- $host : string
-
SMTP server IP or host name
- $port : int = null
-
The port number to connect to
- $timeout : int = 30
-
How long to wait for the connection to open
- $options : array<string|int, mixed> = []
-
An array of options for stream_context_create()
Return values
bool —connected()
Check connection state.
public
connected() : bool
Return values
bool —True if connected
data()
Send an SMTP DATA command.
public
data(string $msg_data) : bool
Issues a data command and sends the msg_data to the server, finalizing the mail transaction. $msg_data is the message that is to be send with the headers. Each header needs to be on a single line followed by a <CRLF> with the message headers and the message body being separated by an additional <CRLF>. Implements RFC 821: DATA <CRLF>.
Parameters
- $msg_data : string
-
Message data to send
Return values
bool —getDebugLevel()
Get debug output level.
public
getDebugLevel() : int
Return values
int —getDebugOutput()
Get debug output method.
public
getDebugOutput() : string
Return values
string —getError()
Get the latest error.
public
getError() : array<string|int, mixed>
Return values
array<string|int, mixed> —getLastReply()
Get the last reply from the server.
public
getLastReply() : string
Return values
string —getLastTransactionID()
Get the queue/transaction ID of the last SMTP transaction If no reply has been received yet, it will return null.
public
getLastTransactionID() : bool|string|null
If no pattern was matched, it will return false.
Tags
Return values
bool|string|null —getServerExt()
Get metadata about the SMTP server from its HELO/EHLO response.
public
getServerExt(string $name) : string|bool|null
The method works in three ways, dependent on argument value and current state:
- HELO/EHLO has not been sent - returns null and populates $this->error.
- HELO has been sent - $name == 'HELO': returns server name $name == 'EHLO': returns boolean false $name == any other string: returns null and populates $this->error
- EHLO has been sent - $name == 'HELO'|'EHLO': returns the server name $name == any other string: if extension $name exists, returns True or its options (e.g. AUTH mechanisms supported). Otherwise returns False.
Parameters
- $name : string
-
Name of SMTP extension or 'HELO'|'EHLO'
Return values
string|bool|null —getServerExtList()
Get SMTP extensions available on the server.
public
getServerExtList() : array<string|int, mixed>|null
Return values
array<string|int, mixed>|null —getTimeout()
Get SMTP timeout.
public
getTimeout() : int
Return values
int —getVerp()
Get VERP address generation mode.
public
getVerp() : bool
Return values
bool —hello()
Send an SMTP HELO or EHLO command.
public
hello([string $host = '' ]) : bool
Used to identify the sending server to the receiving server.
This makes sure that client and server are in a known state.
Implements RFC 821: HELO <SP>
Parameters
- $host : string = ''
-
The host name or IP to connect to
Return values
bool —mail()
Send an SMTP MAIL command.
public
mail(string $from) : bool
Starts a mail transaction from the email address specified in
$from. Returns true if successful or false otherwise. If True
the mail transaction is started and then one or more recipient
commands may be called followed by a data command.
Implements RFC 821: MAIL <SP> FROM:
Parameters
- $from : string
-
Source address of this message
Return values
bool —noop()
Send an SMTP NOOP command.
public
noop() : bool
Used to keep keep-alives alive, doesn't actually do anything.
Return values
bool —quit()
Send an SMTP QUIT command.
public
quit([bool $close_on_error = true ]) : bool
Closes the socket if there is no error or the $close_on_error argument is true. Implements from RFC 821: QUIT <CRLF>.
Parameters
- $close_on_error : bool = true
-
Should the connection close if an error occurs?
Return values
bool —recipient()
Send an SMTP RCPT command.
public
recipient(string $address[, string $dsn = '' ]) : bool
Sets the TO argument to $toaddr.
Returns true if the recipient was accepted false if it was rejected.
Implements from RFC 821: RCPT <SP> TO:
Parameters
- $address : string
-
The address the message is being sent to
- $dsn : string = ''
-
Comma separated list of DSN notifications. NEVER, SUCCESS, FAILURE or DELAY. If you specify NEVER all other notifications are ignored.
Return values
bool —reset()
Send an SMTP RSET command.
public
reset() : bool
Abort any transaction that is currently in progress. Implements RFC 821: RSET <CRLF>.
Return values
bool —True on success
sendAndMail()
Send an SMTP SAML command.
public
sendAndMail(string $from) : bool
Starts a mail transaction from the email address specified in $from.
Returns true if successful or false otherwise. If True
the mail transaction is started and then one or more recipient
commands may be called followed by a data command. This command
will send the message to the users terminal if they are logged
in and send them an email.
Implements RFC 821: SAML <SP> FROM:
Parameters
- $from : string
-
The address the message is from
Return values
bool —setDebugLevel()
Set debug output level.
public
setDebugLevel(int $level) : mixed
Parameters
- $level : int
Return values
mixed —setDebugOutput()
Set debug output method.
public
setDebugOutput([string|callable $method = 'echo' ]) : mixed
Parameters
- $method : string|callable = 'echo'
-
The name of the mechanism to use for debugging output, or a callable to handle it
Return values
mixed —setTimeout()
Set SMTP timeout.
public
setTimeout(int $timeout) : mixed
Parameters
- $timeout : int
-
The timeout duration in seconds
Return values
mixed —setVerp()
Enable or disable VERP address generation.
public
setVerp([bool $enabled = false ]) : mixed
Parameters
- $enabled : bool = false
Return values
mixed —startTLS()
Initiate a TLS (encrypted) session.
public
startTLS() : bool
Return values
bool —turn()
Send an SMTP TURN command.
public
turn() : bool
This is an optional command for SMTP that this class does not support. This method is here to make the RFC821 Definition complete for this class and may be implemented in future. Implements from RFC 821: TURN <CRLF>.
Return values
bool —verify()
Send an SMTP VRFY command.
public
verify(string $name) : bool
Parameters
- $name : string
-
The name to verify
Return values
bool —edebug()
Output debugging info via a user-selected method.
protected
edebug(string $str, int $level) : mixed
Parameters
- $str : string
-
Debug string to output
- $level : int
-
The debug level of this message; see DEBUG_* constants
Tags
Return values
mixed —errorHandler()
Reports an error number and string.
protected
errorHandler(int $errno, string $errmsg[, string $errfile = '' ], int $errline) : mixed
Parameters
- $errno : int
-
The error number returned by PHP
- $errmsg : string
-
The error message returned by PHP
- $errfile : string = ''
-
The file the error occurred in
- $errline : int
-
The line number the error occurred on
Return values
mixed —get_lines()
Read the SMTP server's response.
protected
get_lines() : string
Either before eof or socket timeout occurs on the operation. With SMTP we can tell if we have more lines to read if the 4th character is '-' symbol. If it is a space then we don't need to read anything else.
Return values
string —getSMTPConnection()
Create connection to the SMTP server.
protected
getSMTPConnection(string $host[, int $port = null ][, int $timeout = 30 ][, array<string|int, mixed> $options = [] ]) : false|resource
Parameters
- $host : string
-
SMTP server IP or host name
- $port : int = null
-
The port number to connect to
- $timeout : int = 30
-
How long to wait for the connection to open
- $options : array<string|int, mixed> = []
-
An array of options for stream_context_create()
Return values
false|resource —hmac()
Calculate an MD5 HMAC hash.
protected
hmac(string $data, string $key) : string
Works like hash_hmac('md5', $data, $key) in case that function is not available.
Parameters
- $data : string
-
The data to hash
- $key : string
-
The key to hash with
Return values
string —parseHelloFields()
Parse a reply to HELO/EHLO command to discover server extensions.
protected
parseHelloFields(string $type) : mixed
In case of HELO, the only parameter that can be discovered is a server name.
Parameters
- $type : string
-
HELO
orEHLO
Return values
mixed —recordLastTransactionID()
Extract and return the ID of the last SMTP transaction based on a list of patterns provided in SMTP::$smtp_transaction_id_patterns.
protected
recordLastTransactionID() : bool|string|null
Relies on the host providing the ID in response to a DATA command. If no reply has been received yet, it will return null. If no pattern was matched, it will return false.
Return values
bool|string|null —sendCommand()
Send a command to an SMTP server and check its return code.
protected
sendCommand(string $command, string $commandstring, int|array<string|int, mixed> $expect) : bool
Parameters
- $command : string
-
The command name - not sent to the server
- $commandstring : string
-
The actual command to send
- $expect : int|array<string|int, mixed>
-
One or more expected integer success codes
Return values
bool —True on success
sendHello()
Send an SMTP HELO or EHLO command.
protected
sendHello(string $hello, string $host) : bool
Low-level implementation used by hello().
Parameters
- $hello : string
-
The HELO string
- $host : string
-
The hostname to say we are
Tags
Return values
bool —setError()
Set error messages and codes.
protected
setError(string $message[, string $detail = '' ][, string $smtp_code = '' ][, string $smtp_code_ex = '' ]) : mixed
Parameters
- $message : string
-
The error message
- $detail : string = ''
-
Further detail on the error
- $smtp_code : string = ''
-
An associated SMTP error code
- $smtp_code_ex : string = ''
-
Extended SMTP code