Message could not be sent mailer error smtp error could not authenticate error тильда

Ответили на вопрос 5 человек. Оцените лучшие ответы! И подпишитесь на вопрос, чтобы узнавать о появлении новых ответов.
  • Resident234

PHPMailer не отправляет почту по SMTP yandex, дебагер выдает следующее:

Could not authenticate.

Итак, по почте:
Все данные введены правильно, пароль приложений создан, все почтовые программы включены, почта активна
Сервер:
openssl — включено, сертификат висит

Процесс отправки

$username = '***********@yandex.ru';
$password = '******';

$host = 'smtp.yandex.ru';  // Пробовал 'ssl://smtp.yandex.ru'
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = $host;
$mail->SMTPAuth = true;
$mail->Username = $username;
$mail->Password = $password;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; 
$mail->Port = 465;

$mail->CharSet = 'UTF-8';
$mail->setFrom($username, '*****');
$mail->addAddress($user_email);  // $user_email = '******@yandex.ru'

$mail->isHTML(true); 
$mail->Subject = 'Тест';
$mail->Body = '<b>123</b>';
$mail->AltBody = 'Тестовое сообщение.';
$mail->send();

Что может быть не так?


  • Вопрос задан

    более года назад

  • 1173 просмотра

В общем, кому интересно, проблема в итоге оказалась в хостинге, протестировали на другом и все заработало. К сожалению, владелец старого хостинга не захотел вносить изменения.
Если вы столкнетесь с аналогичной проблемой и вы уверены, что ваш код правильный, проверяйте с помощью OpenSSL, он вам точно покажет в чем проблема. В моем случае, проблема с сертификатами.

Чтобы ящик заработал надо хотя бы один раз зайти в него через веб интерфейс яндекса.

SMTPSecure = ‘TLS’;
Port = 587;
В заголовке from должен быть тот же ящик, что и при авторизации.

Пригласить эксперта

8 часов убил на выяснение. почему мой скрипт отправляет письмо, а не один из плагинов не хочет.
Решение нашёл следующее

скачал библиотеку PHPMailer-6.6.3
переподключил

require_once __DIR__ . '/PHPMailer/Exception.php';
require_once __DIR__ . '/PHPMailer/PHPMailer.php';
require_once __DIR__ . '/PHPMailer/SMTP.php';

use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;

//и главная строчка: 
$phpmailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;  //Без которой письмо на 587й порт по tls не уходит.

//другие параметры:
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();    
$mail->Mailer = 'tls';  
$mail->Host       = 'smtp.yandex.ru';
$mail->SMTPAuth   = true;
$mail->Username   = 'noreply@mydomain.ru';	
$mail->Password   = 'пароль от ящика noreply@mydomain.ru';
    
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port       = 587;

В итоге зашёл в один из плагинов вордпресс, переопределил библиотеку PHPMailer и всё заработало.

Всё дело в том, что мой хостер блочит порты и не разрешает соединяться напрямую с smtp, а для разблокировки портов, просит чуть-ли не наторильную доверенность, сканы 10 документов и т.д.

Попробуйте включить imap в настройках почты (для пущей уверености можете установить галочку и на POP3)

60e614fdab74e563987077.jpeg

Так же у яши есть пароли для приложений, можете попробовать авторизовываться через сгенерированный пароль приложений.

60e61748b8d0e339577726.jpeg

А так же можно попробовать заменить ENCRYPTION_SMTPS на ENCRYPTION_STARTTLS и порт с 465 на 587


  • Показать ещё
    Загружается…

10 февр. 2023, в 00:15

1000 руб./в час

09 февр. 2023, в 22:06

500 руб./за проект

09 февр. 2023, в 22:01

50000 руб./за проект

Минуточку внимания

PHPMailer is a great tool to send emails safely and easily using SMTP authentication.

But, sometimes this may fail due to incompatible server settings or incorrect SMTP configuration.

smtp error: could not authenticate” is one such problem reported by website owners when using PHPmailer to send emails.

At Bobcares, we resolve such email errors as part of our Outsourced Technical Support for web hosting providers.

Today, let’s see the top 5 reasons for this error and how our engineers fix it.

What is this “smtp error: could not authenticate” error?

Simply put, this error says:  “You try to connect to SMTP server, but it can’t authenticate you“.

So, it could mean,

  • The PHP application was able to connect to SMTP server, but the authentication failed.
  • Application was not able to connect to the SMTP server.

What’s wrong here? Let’s have a quick look.

Causes and Fixes for “smtp error: could not authenticate” error in phpmailer

1) Wrong SMTP authentication details

Each mail server uses an authentication system to validate users before they can connect and send emails.

When you send an email from your script, the mail server attempts to identify the user with the account’s username and password.

If this authentication fails, the mail server rejects the connection and users receive the error “smtp error: could not authenticate“.

Solution

We’ll ensure that correct username and password are given in the mail script.

In case of default email accounts, the full username(user@domain.com) should be given in the application.

Also, if the password was recently modified, it should be updated in the email application.

2) Wrong SMTP port and SMTP Host

Users should enter the mail server details in the “$mail->Host” field of the email application.

For example, if you use Gmail as your mail server, the hostname should be “smtp.gmail.com“.

Sometimes, a typo in the hostname or an inactive mail server result in this error.

Similarly, for port numbers, the default SMTP port is 25, but some mail servers use custom ports, such as 587, to avoid spam.

Also, some mail servers will be configured to allow emails only via SSL port 465.

It is also possible that some email providers restrict access to their SMTP port using firewall rules.

Incorrect port entry in SMTP settings or firewall restrictions may cause email delivery errors.

Solution

We’ll ensure the DNS connectivity of the mail server with the command.

dig mail.domain.com

Also, to identify the correct SMTP port and confirm connectivity to the SMTP port, we use the command:

telnet domain.com 25

We cross-check the SMTP settings in the application and make sure that correct SMTP host and port is used.

If we find any firewall restrictions, the IP should be whitelisted in the firewall.

3) SMTP encryption settings

For secure email transmission, most users prefer SMTP with encryption. SSL and TLS are the 2 encryption protocols used.

But, on some mail servers, SSL/TLS support may not be enabled or the existing SSL certificate may have expired.

What if users specify encryption in their application? Result is “smtp error: could not authenticate” error.

Solution

Our Support Engineers ensure that Apache and PHP are properly configured on the server with ‘mod_ssl‘ and ‘openssl‘ so that SSL can work on the server.

We’ll also verify the validity of mail server’s SSL certificate using the command:

openssl s_client -connect mail.example.com:25 -starttls smtp

So, the solution here is to properly configure SSL for the server or remove the encryption used in the SMTP settings.

4) Google blocks insecure access

Gmail enforces strict security restrictions.

If an app doesn’t meet these security standards, it may block access because these apps are easier to break into.

Users who authenticate to Gmail server receive the error “smtp error: could not authenticate” because Google considers username and password login as insecure.

Solution

Ideally, we reconfigure the app so that it meets the Google standards. If this is not possible, we’ll help website owners to loosen the security restrictions using the below steps.

  • Sign in to the Google admin console.
  • Go to Security > Basic settings.
  • Go to Less Secure Apps.
  • Turn on Allow less secure apps.

phpmailer smtp error: could not authenticate

Allow less secure apps in gmail account

5) Expired Password

This can happen once in a while.

Some servers are set to auto expire passwords and app maintainers forget to update them in time.

When the application tries to connect, the mail server could not validate the password.

Result is “smtp error: could not authenticate” error.

Solution

This usually happens when the account owner missed the notification email about password expiry.

In such cases, we reset the password and also update it in the email application.

We also make sure that the notification email is set correctly, and in some cases, we remove the password expiration set for the mailbox.

Conclusion

smtp error: could not authenticate” is a common error when users send emails via PHPMailer using SMTP authentication. This error occurs when the application can’t establish an SMTP connection to the mail server. Today, we’ve seen the top 5 causes of this error and how our Support Engineers fix them.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

SEE SERVER ADMIN PLANS

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

dainis12

0 / 0 / 0

Регистрация: 20.03.2018

Сообщений: 27

1

14.04.2018, 20:57. Показов 9424. Ответов 11

Метки нет (Все метки)


Вот код

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
require'PHPMailer/class.phpmailer.php';
//require'includes/messege.php';
$mail = new PHPMailer();
 
 
$mail->isSMTP();
$mail->Host = 'ssl://smtp.gmail.com';//
$mail->SMTPAuth = true;
$mail->Username = "...";
$mail->Password = "...";
$mail->SMTPSequre = 'SSL';
$mail->Port = '465';
$mail->From = "...@gmail.com";
$mail->FromName = "...";
$mail->AddAddress("...@mail.ru");
$mail->isHTML(true);
$mail->Subject = "Тема письма";
$mail->Body = "Привет мир";
$mail->AltBody = "This is the body when user views in plain text format";
echo "all_ok";
if(!$mail->Send())
{
   echo "Message could not be sent. <p>";
   echo "Mailer Error: " . $mail->ErrorInfo;
   exit;
}
 
echo "Message has been sent";
exit();

Подскажите пожалуйста в чем может быть проблема

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Jodah

Эксперт PHP

3802 / 3160 / 1326

Регистрация: 01.08.2012

Сообщений: 10,717

14.04.2018, 21:31

2

PHP
1
$mail->SMTPDebug = 2;

И смотрите выведенные логи.



0



0 / 0 / 0

Регистрация: 20.03.2018

Сообщений: 27

14.04.2018, 21:40

 [ТС]

3

Хм хм, как бы спросить что это все означает и при этом не раскрыть данные…
Хотя в открытом виде паролей вроде нет��

Добавлено через 3 минуты
Немного понял, но далеко не все!
SMTP -> FROM SERVER:220 smtp.gmail.com ESMTP h86-v6sm1888277lfl.73 — gsmtp
SMTP -> FROM SERVER: 250-smtp.gmail.com at your service, [37.75.200.79] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-CHUNKING 250 SMTPUTF8
SMTP -> ERROR: Password not accepted from server: 534-5.7.14 Please log in via your web browser and 534-5.7.14 then try again. 534-5.7.14 Learn more at 534 5.7.14 https://support.google.com/mail/answer/78754 h86-v6sm1888277lfl.73 — gsmtp
SMTP -> FROM SERVER:250 2.1.5 Flushed h86-v6sm1888277lfl.73 — gsmtp
SMTP Error: Could not authenticate. Message could not be sent.

по ссылке для справки пишет: страница не найдена!

Добавлено через 1 минуту
Ааа нм нм прошу прощения ссылочка активная!



0



Эксперт PHP

3802 / 3160 / 1326

Регистрация: 01.08.2012

Сообщений: 10,717

14.04.2018, 21:56

4

dainis12, если не ошибаюсь, ваш пункт «Разрешите небезопасные приложения».



0



0 / 0 / 0

Регистрация: 20.03.2018

Сообщений: 27

15.04.2018, 13:41

 [ТС]

5

Я правильно понимаю что мне нужно Включить IMAP. Но для этого нужен аккаунт в G Suite, однако уже для G Suite необходимо иметь компанию, которой у меня пока что нет! Можно ли мне каким либо способом включить эту фунцию, не затрагивая каких либо компаний?



0



Эксперт PHP

3802 / 3160 / 1326

Регистрация: 01.08.2012

Сообщений: 10,717

15.04.2018, 13:45

6

Цитата
Сообщение от dainis12
Посмотреть сообщение

Но для этого нужен аккаунт в G Suite

Не знаю, что это. Доступ по IMAP включается в настройках в веб-интерфейсе почты.



0



0 / 0 / 0

Регистрация: 20.03.2018

Сообщений: 27

15.04.2018, 13:51

 [ТС]

7

Включение доступа по протоколам POP и IMAP

Войдите в Консоль администратора Google.

Войдите в аккаунт администратора (ваш текущий аккаунт …@gmail.com не подходит).
В консоли администратора откройте Приложения дальше G Suite дальше Gmail дальше Расширенные настройки.

Совет. Ссылка на раздел «Расширенные настройки» находится в самом низу страницы Gmail.
В разделе Организации выберите нужное подразделение.
В разделе Доступ по протоколу POP и IMAP установите или сними

Это написано в https://support.google.com/a/answer/105694?hl=ru



0



Эксперт PHP

3802 / 3160 / 1326

Регистрация: 01.08.2012

Сообщений: 10,717

15.04.2018, 14:21

8

dainis12, так в заголовке написано, что речь идёт как раз про G Suite, это не ваш случай.

Месяца 3 назад подключал гуглопочту. Если не ошибаюсь, нужно было сделать всего 2 вещи:
1. Включить IMAP в веб-интерфейсе почты
2. Разрешить доступ ненадёжным приложениям, вроде эта ссылка: https://support.google.com/accounts/answer/6010255

Может быть что-то упустил, но с G Suite не пересекался, это же другой продукт.



1



dainis12

0 / 0 / 0

Регистрация: 20.03.2018

Сообщений: 27

15.04.2018, 14:57

 [ТС]

9

Warning: fputs() expects parameter 1 to be resource, integer given in C:OSPaneldomainssotset.ruPHPMailerclass.smtp. php on line 212
Вот такую ошибку теперь выдает!

/**

PHP
1
2
3
4
5
6
7
 public $Username      = '';
 
  /**
   * Sets SMTP password.
   * @var string
   */
  public $Password      = '';

Вот такой код находится в этом файле! Однако как раз строчка 212 пустая, но вот уже на 215 появляется переменная var в которой вроде как хранится пароль, пароль действительно у меня состоял только из одних цифр, однако я его поменял на буквенный, перезапустил сервер и пару раз обновил, но ошибка осталась!

Добавлено через 58 секунд
Строчке 212 соответствует строчка 2!

Добавлено через 3 минуты
По поводу G Suite прошу прощения, просто в поиске вбил про IMAP-доступ и гугловский первой ссылкой G Suite стал пиарить!



0



91 / 91 / 13

Регистрация: 14.07.2012

Сообщений: 539

15.04.2018, 21:35

10

dainis12, зачем Вы в коде ковыряетесь? Там все работает. Смотрите хелп по майлеру, там написанно как работать с гмайлом. У него свои приколы.



0



Эксперт PHP

3802 / 3160 / 1326

Регистрация: 01.08.2012

Сообщений: 10,717

16.04.2018, 07:27

11

dainis12, если вы ничего не меняли в этом файле, скорее всего вы некорректно указали какие-то настройки. smtp-сервер, порт или что-то ещё.



0



91 / 91 / 13

Регистрация: 14.07.2012

Сообщений: 539

17.04.2018, 05:29

12

Если в коде 6 строку убрать, то скорей всего заработает. У меня так было. Не знаю почему.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

17.04.2018, 05:29

Помогаю со студенческими работами здесь

Ошибка: Fatal error: Uncaught Error: Call to undefined function mysql_num_rows() in
Пытаюсь вывести картинку из базы данных.
Код PHP:

&lt;?php

Ошибка в php скрипте: Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING
Возникла ошибка в php скрипте на вывод текста из БД
Сама ошибка: Parse error: syntax error,…

Ошибка: FATAL ERROR Uncaught Error: Call to undefined function Test()
Доброго времени суток! Народ на одном из популярных порталов изучал примеры ООП, попробовав на…

В чем ошибка (Parse error: syntax error, unexpected ‘$i’ (T_VARIABLE), expecting ‘;’) ?
private function select($table_name,$fields,$where=&quot;&quot;,$order=&quot;&quot;,$up=true,$limit=&quot;&quot;)
{…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

12

Понравилась статья? Поделить с друзьями:
  • Merged partition content как исправить
  • Merge key error
  • Merge error refusing to merge unrelated histories
  • Message center error
  • Mercury ошибка 478 как исправить