- Saved searches
- Use saved searches to filter your results more quickly
- License
- pear/Net_SMTP
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.rst
- About
- Отправка писем через SMTP на PHP
- Сколько писем можно отправлять с бесплатных (SMTP) почтовых ящиков?
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
License
pear/Net_SMTP
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.rst
- 1 Dependencies
- 1.1 The PEAR_Error Class
- 1.2 The Net_Socket Package
- 1.3 The Auth_SASL Package
- 3.1 GSSAPI
- 3.2 DIGEST-MD5
- 3.3 CRAM-MD5
- 3.4 LOGIN
- 3.5 PLAIN
- 3.6 XOAUTH2
- 9.1 Basic Use
The Net_SMTP package uses the PEAR_Error class for all of its error handling.
The Net_Socket package is used as the basis for all network communications. Connection options can be specified via the $socket_options construction parameter:
$socket_options = array('ssl' => array('verify_peer_name' => false)); $smtp = new Net_SMTP($host, null, null, false, 0, $socket_options);
Note: PHP 5.6 introduced OpenSSL changes. Peer certificate verification is now enabled by default. Although not recommended, $socket_options can be used to disable peer verification (as shown above).
The Auth_SASL package is an optional dependency. If it is available, the Net_SMTP package will be able to support the DIGEST-MD5 and CRAM-MD5 SMTP authentication methods. Otherwise, only the LOGIN and PLAIN methods will be available.
All of the Net_SMTP class’s public methods return a PEAR_Error object if an error occurs. The standard way to check for a PEAR_Error object is by using PEAR::isError():
if (PEAR::isError($error = $smtp->connect())) < die($error->getMessage()); >
The Net_SMTP package supports the SMTP authentication standard (as defined by RFC-2554). The Net_SMTP package supports the following authentication methods, in order of preference:
The GSSAPI authentication method uses Kerberos 5 protocol (RFC-4120). Does not use user/password. Requires Service Principal gssapi_principal parameter and has an optional Credentials Cache gssapi_cname parameter. Requires DNS and Key Distribution Center (KDC) setup. It is considered the most secure method of SMTP authentication.
Note: The GSSAPI authentication method is only supported if the krb5 php extension is available.
The DIGEST-MD5 authentication method uses RSA Data Security Inc.’s MD5 Message Digest algorithm. It is considered a more secure method of SMTP authentication than PLAIN or LOGIN, while still vulnerable to MitM attacks without TLS/SSL.
Note: The DIGEST-MD5 authentication method is only supported if the AUTH_SASL package is available.
The CRAM-MD5 authentication method has been superseded by the DIGEST-MD5 method in terms of security. It is provided here for compatibility with older SMTP servers that may not support the newer DIGEST-MD5 algorithm.
Note: The CRAM-MD5 authentication method is only supported if the AUTH_SASL package is available.
The LOGIN authentication method encrypts the user’s password using the Base64 encoding scheme. Because decrypting a Base64-encoded string is trivial, LOGIN is not considered a secure authentication method and should be avoided.
The PLAIN authentication method sends the user’s password in plain text. This method of authentication is not secure and should be avoided.
The XOAUTH2 authentication method sends a username and an OAuth2 access token as per Gmail’s SASL XOAUTH2 documentation.
If secure socket transports have been enabled in PHP, it is possible to establish a secure connection to the remote SMTP server:
$smtp = new Net_SMTP('ssl://mail.example.com', 465);
This example connects to mail.example.com on port 465 (a common SMTPS port) using the ssl:// transport.
TLS/SSL is enabled for authenticated connections by default (via the auth() method’s $tls parameter), but the STARTTLS command can also be sent manually using the starttls() method.
Message data is sent using the data() method. The data can be supplied as a single string or as an open file resource.
If a string is provided, it is passed through the data quoting system and sent to the socket connection as a single block. These operations are all memory-based, so sending large messages may result in high memory usage.
If an open file resource is provided, the data() method will read the message data from the file line-by-line. Each chunk will be quoted and sent to the socket connection individually, reducing the overall memory overhead of this data sending operation.
Header data can be specified separately from message body data by passing it as the optional second parameter to data() . This is especially useful when an open file resource is being used to supply message data because it allows header fields (like Subject:) to be built dynamically at runtime.
$smtp->data($fp, "Subject: My Subject");
By default, all outbound string data is quoted in accordance with SMTP standards. This means that all native Unix ( \n ) and Mac ( \r ) line endings are converted to Internet-standard CRLF ( \r\n ) line endings. Also, because the SMTP protocol uses a single leading period ( . ) to signal an end to the message data, single leading periods in the original data string are «doubled» (e.g. » .. «).
These string transformation can be expensive when large blocks of data are involved. For example, the Net_SMTP package is not aware of MIME parts (it just sees the MIME message as one big string of characters), so it is not able to skip non-text attachments when searching for characters that may need to be quoted.
Because of this, it is possible to extend the Net_SMTP class in order to implement your own custom quoting routine. Just create a new class based on the Net_SMTP class and reimplement the quotedata() method:
require 'Net_SMTP.php'; class Net_SMTP_custom extends Net_SMTP < function quotedata($data) < /* Perform custom data quoting */ >>
Note that the $data parameter will be passed to the quotedata() function by reference. This means that you can operate directly on $data . It also the overhead of copying a large $data string to and from the quotedata() method.
The Net_SMTP package retains the server’s last response for further inspection. The getResponse() method returns a 2-tuple (two element array) containing the server’s response code as an integer and the response’s arguments as a string.
Upon a successful connection, the server’s greeting string is available via the getGreeting() method.
The Net_SMTP package contains built-in debugging output routines (disabled by default). Debugging output must be explicitly enabled via the setDebug() method:
The debugging messages will be sent to the standard output stream by default. If you need more control over the output, you can optionally install your own debug handler.
function debugHandler($smtp, $message) < echo "[$smtp->host] $message\n"; > $smtp->setDebug(true, "debugHandler");
The following script demonstrates how a simple email message can be sent using the Net_SMTP package:
require 'Net/SMTP.php'; $host = 'mail.example.com'; $from = 'user@example.com'; $rcpt = array('recipient1@example.com', 'recipient2@example.com'); $subj = "Subject: Test Message\n"; $body = "Body Line 1\nBody Line 2"; /* Create a new Net_SMTP object. */ if (! ($smtp = new Net_SMTP($host))) < die("Unable to instantiate Net_SMTP object\n"); >/* Connect to the SMTP server. */ if (PEAR::isError($e = $smtp->connect())) < die($e->getMessage() . "\n"); > /* Send the 'MAIL FROM:' SMTP command. */ if (PEAR::isError($smtp->mailFrom($from))) < die("Unable to set sender to \n"); > /* Address the message to each of the recipients. */ foreach ($rcpt as $to) < if (PEAR::isError($res = $smtp->rcptTo($to))) < die("Unable to add recipient : " . $res->getMessage() . "\n"); > > /* Set the body of the message. */ if (PEAR::isError($smtp->data($subj . "\r\n" . $body))) < die("Unable to send data\n"); >/* Disconnect from the SMTP server. */ $smtp->disconnect();
About
Отправка писем через SMTP на PHP
Некоторое время назад, я заметил, что письма, отправляемые с моего сервера, перестали доходить до адресата. Редко, попадали в папку Спам, чаще совсем не доходили. Сразу было понятно, что проблема в функции mail();
Пути решения было два: Читать много мануалов и настраивать сервак так, чтобы функция mail() корректно отправляла всю корреспонденцию или отправлять письма через SMTP. Как вы понимаете, путь я выбрал второй.
$config [ ‘smtp_debug’ ] = true ; //Если Вы хотите видеть сообщения ошибок, укажите true вместо false
$config [ ‘smtp_from’ ] = ‘МегаСервис’ ; //Ваше имя — или имя Вашего сайта. Будет показывать при прочтении в поле «От кого»
$SEND . = ‘Subject: =?’ . $config [ ‘smtp_charset’ ] . ‘?B?’ . base64_encode ( $subject ) . «=?=\r\n» ;
$SEND . = «From: \»=?» . $config [ ‘smtp_charset’ ] . «?B?» . base64_encode ( $config [ ‘smtp_from’ ] ) . «=?=\» <" . $config [ 'smtp_username' ] . ">\r\n» ;">
if ( ! $socket = fsockopen ( $config [ ‘smtp_host’ ] , $config [ ‘smtp_port’ ] , $errno , $errstr , 30 ) )
if ( $config [ ‘smtp_debug’ ] ) echo ‘Не могу отправить HELO!
‘ ;
if ( $config [ ‘smtp_debug’ ] ) echo ‘Не могу найти ответ на запрос авторизаци.
‘ ;
if ( $config [ ‘smtp_debug’ ] ) echo ‘Логин авторизации не был принят сервером!
‘ ;
if ( $config [ ‘smtp_debug’ ] ) echo ‘Пароль не был принят сервером как верный! Ошибка авторизации!
‘ ;
if ( $config [ ‘smtp_debug’ ] ) echo ‘Не могу отправить комманду MAIL FROM:
‘ ;
if ( $config [ ‘smtp_debug’ ] ) echo ‘Не могу отправить комманду RCPT TO:
‘ ;
if ( $config [ ‘smtp_debug’ ] ) echo ‘Не могу отправить комманду DATA
‘ ;
if ( $config [ ‘smtp_debug’ ] ) echo ‘Не смог отправить тело письма. Письмо не было отправленно!
‘ ;
if ( $config [ ‘smtp_debug’ ] ) echo «Проблемы с отправкой почты!
$response
$line
» ;
if ( $config [ ‘smtp_debug’ ] ) echo «Проблемы с отправкой почты!
$response
$line
» ;Использовать её можно так-же как и обычную функцию mail:
smtpmail ( ‘Имя получателя’ , ’email-получателя@mail.ru’ , ‘Тема письма’ , ‘HTML или обычный текст письма’ ) ;
Сколько писем можно отправлять с бесплатных (SMTP) почтовых ящиков?
- mail.ru — не более 1 письма в минуту
- yandex.ru — не более 150 писем в сутки, не более 25 адресатов в одном письме
- gmail.com, tut.by — не более 500 писем в сутки (хотя в справке гугла фигурирует 2000), не более 500 получателей в одном письме за раз при отправке через интерфейс gmail.com (через web-интерфейс, т.е. при входе через браузер), не более 100 получателей в одном письме за раз при отправке через ваш почтовый клиент
- rambler.ru — не более 200 писем в час
- ukr.net — не более 250 писем в сутки
- meta.ua — не более 200 писем в сутки
- aol.com — не более 500 писем в сутки
- lycos.com — не более 250 писем в сутки
Рекомендую отправлять количества писем на 20-30 % меньше лимита.
Gmail может заблокировать (первый раз на сутки) ваш аккаунт и при меньшем чем 500 числе адресатов в письме. Очень важно, чтобы адреса были живые, работающие. При нескольких десятках мертвых адресов в одном письме c gmail вероятность блокировки очень велика.