Библиотека программиста

15.10.2026 - Отправка писем с использованием smtp-сервера

вы можете воспользоваться нашим примером, в котором реализована отправка писем с использованием smtp-сервера, для которого требуется авторизация. Поэтому не забудьте добавить в скрипт соответствующие реквизиты доступа

, например:

PHP - Код
function authSendEmail($from, $namefrom, $to, $nameto, 
$subject, $message)
{
$smtpServer = "smtp.domain.tld";
$port = "25";
$timeout = "30";
$username = "postmaster@domain.tld";
$password = "YouPassword";
$localhost = "localhost";
$newLine = "\r\n";

//Connect to the host on the specified port
$smtpConnect = fsockopen($smtpServer, $port, $errno, 
$errstr, $timeout);
$smtpResponse = fgets($smtpConnect, 515);
if(empty(
$smtpConnect))
{
$output = "Failed to connect: $smtpResponse";
return 
$output;
}
else
{
$logArray['connection'] = "Connected: $smtpResponse";
}

//Request Auth Login
fputs($smtpConnect,"AUTH LOGIN" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);
$logArray['authrequest'] = "$smtpResponse";

//Send username
fputs($smtpConnect, base64_encode($username) . $newLine);
$smtpResponse = fgets($smtpConnect, 515);
$logArray['authusername'] = "$smtpResponse";

//Send password
fputs($smtpConnect, base64_encode($password) . $newLine);
$smtpResponse = fgets($smtpConnect, 515);
$logArray['authpassword'] = "$smtpResponse";

//Say Hello to SMTP
fputs($smtpConnect, "HELO $localhost" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);
$logArray['heloresponse'] = "$smtpResponse";

//Email From
fputs($smtpConnect, "MAIL FROM: $from" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);
$logArray['mailfromresponse'] = "$smtpResponse";

//Email To
fputs($smtpConnect, "RCPT TO: $to" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);
$logArray['mailtoresponse'] = "$smtpResponse";

//The Email
fputs($smtpConnect, "DATA" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);
$logArray['data1response'] = "$smtpResponse";

//Construct Headers
$headers = "MIME-Version: 1.0" . $newLine;
$headers .= "Content-type: text/html; 
charset=windows-1251" 
. $newLine;
$headers .= "To: $nameto <$to>" . $newLine;
$headers .= "From: $namefrom <$from>" . $newLine;

fputs($smtpConnect, "To: $to&#092;nFrom: $from&#092;nSubject: 
$subject&#092;n$headers&#092;n&#092;n$message&#092;n.&#092;n");

$smtpResponse = fgets($smtpConnect, 515);
$logArray['data2response'] = "$smtpResponse";

// Say Bye to SMTP
fputs($smtpConnect,"QUIT" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);
$logArray['quitresponse'] = "$smtpResponse";
}

//new function

$to = "postmaster@domain.tld";
$nameto = "Demo User";
$from = "postmaster@domain.tld";
$namefrom = "Postmaster";
$subject = "Hello World Again!";
$message = "World, Hello!";

authSendEmail($from, $namefrom, $to, $nameto, 
$subject, $message);

Опубликовано на сайте: http://www.coders-library.ru
Прямая ссылка: http://www.coders-library.ru/index.php?name=news&op=view&id=331