U
U
uzolenta2019-12-05 15:51:06
PHP
uzolenta, 2019-12-05 15:51:06

How to send mail via smtp to mail.ru/gmail?

Hello! How to implement sending mail via SMTP to mail.ru and gmail?
Here is the code I am using. The code works for yandex, my mail server. But when you try to connect to mail.ru and gmail - gives a password error. In gmail, I included the ability to use third-party applications (it seems that this setting is called), in mail.ru I did not make any additional settings (are there any? - I haven’t seen them). An attempt to connect to mail.ru was accurate, as it received a response from mail.ru and the mailbox was temporarily blocked for questionable login attempts.

<?php

$config['smtp_username'] = 'ПОЧТА@mail.ru'; //Смените на имя своего почтового ящика. (ваш email)

$config['smtp_port'] = '465'; // Порт работы. Не меняйте, если не уверены. На 2014 порт вроде 465. ЕСЛИ ВООБЩЕ НЕ РАБОТАЕТ - убрать кавычки в 25
$config['smtp_host'] = 'ssl://smtp.mail.ru';
$config['smtp_password'] = 'ПАРОЛЬ ОТ ПОЧТЫ'; //Измените пароль (от вашего ящика)
$config['smtp_debug'] = true; //Если Вы хотите видеть сообщения ошибок, укажите true вместо false
$config['smtp_charset'] = 'UTF-8'; //кодировка сообщений. (или UTF-8, итд) (меняется также в самом низу)
$config['smtp_from'] = 'ПОЧТА@mail.ru'; //Ваше имя - или имя Вашего сайта. Будет показывать при прочтении в поле "От кого"
function smtpmail($mail_to, $subject, $message, $headers='') {
global $config;
$SEND = "Date: ".date("D, d M Y H:i:s") . " UT\r\n";
$SEND .= 'Subject: =?'.$config['smtp_charset'].'?B?'.base64_encode($subject)."=?=\r\n";
if ($headers) $SEND .= $headers."\r\n\r\n";
else
{
$SEND .= "Reply-To: ".$config['smtp_username']."\r\n";
$SEND .= "MIME-Version: 1.0\r\n";
$SEND .= "Content-Type: text/plain; charset=\"".$config['smtp_charset']."\"\r\n";
$SEND .= "Content-Transfer-Encoding: 8bit\r\n";
$SEND .= "From: \"".$config['smtp_from']."\" <".$config['smtp_username'].">\r\n";
//$SEND .= "From: ".$config['smtp_username']."\r\n";
$SEND .= "To: $mail_to <$mail_to>\r\n";
$SEND .= "X-Priority: 3\r\n\r\n";
}
$SEND .= $message."\r\n";
if( !$socket = fsockopen($config['smtp_host'], $config['smtp_port'], $errno, $errstr, 30) ) {
if ($config['smtp_debug']) echo $errno."<br>".$errstr;
return false;
}

if (!server_parse($socket, "220", __LINE__)) return false;

fputs($socket, "EHLO " . $config['smtp_host'] . "\r\n");
if (!server_parse($socket, "250", __LINE__)) {
if ($config['smtp_debug']) echo '<p>Не могу отправить HELO!</p>';
fclose($socket);
return false;
}
fputs($socket, "AUTH LOGIN\r\n");
if (!server_parse($socket, "334", __LINE__)) {
if ($config['smtp_debug']) echo '<p>Не могу найти ответ на запрос авторизаци.</p>';
fclose($socket);
return false;
}
fputs($socket, base64_encode($config['smtp_username']) . "\r\n");
if (!server_parse($socket, "334", __LINE__)) {
if ($config['smtp_debug']) echo '<p>Логин авторизации не был принят сервером!</p>';
fclose($socket);
return false;
}
fputs($socket, base64_encode($config['smtp_password']) . "\r\n");
//fputs($socket, $config['smtp_password']."\r\n");
if (!server_parse($socket, "235", __LINE__)) {
if ($config['smtp_debug']) echo '<p>Пароль не был принят сервером как верный! Ошибка авторизации!</p>';
fclose($socket);
return false;
}
fputs($socket, "MAIL FROM: <".$config['smtp_username'].">\r\n");
if (!server_parse($socket, "250", __LINE__)) {
if ($config['smtp_debug']) echo '<p>Не могу отправить комманду MAIL FROM: </p>';
fclose($socket);
return false;
}
fputs($socket, "RCPT TO: <" . $mail_to . ">\r\n");

if (!server_parse($socket, "250", __LINE__)) {
if ($config['smtp_debug']) echo '<p>Не могу отправить комманду RCPT TO: </p>';
fclose($socket);
return false;
}
fputs($socket, "DATA\r\n");

if (!server_parse($socket, "354", __LINE__)) {
if ($config['smtp_debug']) echo '<p>Не могу отправить комманду DATA</p>';
fclose($socket);
return false;
}
fputs($socket, $SEND."\r\n.\r\n");

if (!server_parse($socket, "250", __LINE__)) {
if ($config['smtp_debug']) echo '<p>Не смог отправить тело письма. Письмо не было отправленно!</p>';
fclose($socket);
return false;
}
fputs($socket, "QUIT\r\n");
fclose($socket);
return TRUE;
}

function server_parse($socket, $response, $line = __LINE__) {
global $config;
while (@substr($server_response, 3, 1) != ' ') {
if (!($server_response = fgets($socket, 256))) {
if ($config['smtp_debug']) echo "<p>Проблемы с отправкой почты!</p>$response<br>$line<br>";
return false;
}
}
if (!(substr($server_response, 0, 3) == $response)) {
if ($config['smtp_debug']) echo "<p>Проблемы с отправкой почты!</p>$response<br>$line<br>";
return false;
}
return true;
}


$emailTo = 'ПОЧТА@bk.ru';
$resultSendEmail = smtpmail($emailTo, 'тема письма', 'текст письма');
  if($resultSendEmail === true){
    echo "Done";
  }else{
    echo "Error: " . $resultSendEmail;
  }
?>

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
FanatPHP, 2019-12-05
@FanatPHP

Three simple steps to solve this problem:
1. Look at the calendar and clarify what century it is in the yard.
2. Carefully select this code, and press the Del key
3. Download phpmailer
4. Take an example from the same
place 5. Forget all these handicrafts like a bad dream.
it should be understood that sending mail is not just copying into your script some specific combinations of characters that accidentally worked in the last century for the author of some antediluvian article. This is a much more complex process, which includes many nuances. And therefore, sending mail should not be manually sculpted on the go from manure and sticks, but entrusted to a proven and debugged solution.

E
Eugene, 2019-12-05
@Nc_Soft

Try port 587

A
AUser0, 2019-12-05
@AUser0

Change the line (it's about the 35th):
to code:
fputs($socket, "EHLO " .gethostname(). "\r\n");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question