Please check these things before submitting your issue:
- Make sure you’re using the latest version of PHPMailer
- Check that your problem is not dealt with in the troubleshooting guide, especially if you’re having problems connecting to Gmail or GoDaddy
- Include sufficient code to reproduce your problem
- If you’re having an SMTP issue, include the debug output generated with
SMTPDebug = 2
set - If you have a question about how to use PHPMailer (rather than reporting a bug in it), tag a question on Stack Overflow with
phpmailer
, but search first!
Problem description
When i trying send message from smtp.gmail.com, with ssl, or tls, or different ports, doesnt matter, it’s throw exception to me.
I have Allowed less secure apps in gmail, and i visit captcha confirmation
Code to reproduce
$mail->isSMTP(); $mail->SMTPDebug = 2; $mail->Host = "smtp.gmail.com"; $mail->SMTPAuth = true; $mail->SMTPSecure = "ssl"; $mail->Port = 465; $mail->CharSet = "UTF-8"; $mail->Username = "example@gmail.com"; $mail->Password = "*******"; $mail->setFrom("example@gmail.com", "Alex"); $mail->Subject = "Тест, отправка письма"; $mail->msgHTML("Message"); $mail->addAddress("example@mail.ru"); if (!$mail->send()) { $mail->ErrorInfo; } else { echo "123"; }
Debug output
2017-10-23 19:44:18 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP q24sm1694776lff.48 - gsmtp
2017-10-23 19:44:18 CLIENT -> SERVER: EHLO *my_server*
2017-10-23 19:44:18 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [*my_server*]250-SIZE 35882577250-8BITMIME250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2017-10-23 19:44:18 CLIENT -> SERVER: AUTH LOGIN
2017-10-23 19:44:18 SERVER -> CLIENT: 334 VXNlcm5hbWU6
2017-10-23 19:44:18 CLIENT -> SERVER: YXJldm9sdXRpb25wcm9qZWN0QGdtYWlsLmNvbQ==
2017-10-23 19:44:18 SERVER -> CLIENT: 334 UGFzc3dvcmQ6
2017-10-23 19:44:18 CLIENT -> SERVER: cmV2b2x1dGlvbjEyMw==
2017-10-23 19:44:18 SERVER -> CLIENT: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbtI534-5.7.14 qNIYrbZEk6FWx5rHcj6iG24Wnch4-cJAfM8uoUKM9jkHSMq_RaHs_A6dTS2Os70c6MUtaD534-5.7.14 5g_o5siaKUXvyrEugwt0FU-QBcUwp5HHAFfiHmTpuRu57eG1k4pH6sv5fXSQn2dgrZDEtn534-5.7.14 29ptACC7djB5Hv_usdmgN5yckn6u5Q79E3JqMGpS8nN7ZagN2geB2kO3-jkRJN8grPtIVK534-5.7.14 rAXLtSmpqVqRunISlK0V0x80FTYLY> Please log in via your web browser and534-5.7.14 then try again.534-5.7.14 Learn more at534 5.7.14 https://support.google.com/mail/answer/78754 q24sm1694776lff.48 - gsmtp
2017-10-23 19:44:18 SMTP ERROR: Password command failed: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbtI534-5.7.14 qNIYrbZEk6FWx5rHcj6iG24Wnch4-cJAfM8uoUKM9jkHSMq_RaHs_A6dTS2Os70c6MUtaD534-5.7.14 5g_o5siaKUXvyrEugwt0FU-QBcUwp5HHAFfiHmTpuRu57eG1k4pH6sv5fXSQn2dgrZDEtn534-5.7.14 29ptACC7djB5Hv_usdmgN5yckn6u5Q79E3JqMGpS8nN7ZagN2geB2kO3-jkRJN8grPtIVK534-5.7.14 rAXLtSmpqVqRunISlK0V0x80FTYLY> Please log in via your web browser and534-5.7.14 then try again.534-5.7.14 Learn more at534 5.7.14 https://support.google.com/mail/answer/78754 q24sm1694776lff.48 - gsmtp
SMTP Error: Could not authenticate.
2017-10-23 19:44:18 CLIENT -> SERVER: QUIT
2017-10-23 19:44:19 SERVER -> CLIENT: 221 2.0.0 closing connection q24sm1694776lff.48 - gsmtp
SMTP Error: Could not authenticate.
I am failing to send email in my application hosted on appfog
i am using the following code which works fine on localhost but fail on appfog.
JPhpMailer extend class.PhpMailer.php
$mailer = new JPhpMailer(true);
$mailer->IsSMTP();
$mailer->Mailer = "smtp";
//$mailer->SMTPSecure == 'tls';
$mailer->Host = 'ssl://smtp.gmail.com';
$mailer->Port = '465';
$mailer->SMTPAuth = true;
//$mailer->SMTPSecure = true;
$mailer->Username = 'me@gmail.com';
$mailer->Password = 'zzzzzzz';
$mailer->SetFrom($to['from'], $to['from_name']);
$mailer->AddAddress($to['to'],$to['to_name'] );
$mailer->Subject = $to['subject'];
$mailer->Body = $to['body'];
$mailer->Send();
here is the line that in phpMailer that fails to execute`if ($tls) {
if (!$this->smtp->StartTLS()) {
throw new phpmailerException($this->Lang(‘tls’));
}
//We must resend HELO after tls negotiation
$this->smtp->Hello($hello);
}
$connection = true;
if ($this->SMTPAuth) {
if (!$this->smtp->Authenticate($this->Username, $this->Password)) {
**strong text throw new phpmailerException($this->Lang('authenticate')); ** }
}
}
$index++;
if (!$connection) {
throw new phpmailerException($this->Lang('connect_host'));
}
asked Jan 9, 2013 at 10:56
EliethesaiyanEliethesaiyan
2,3341 gold badge20 silver badges35 bronze badges
3
The code below is working for me :
require("phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->SMTPSecure = "tls";
$mail->Host = "smtp.gmail.com"; // specify main and backup server
$mail->Port = 587;
$mail->Username = "myemail@gmail.com"; // SMTP username
$mail->Password = "mypass"; // SMTP password
$mail->From = "myemail@gmail.com";
$mail->FromName = "myname";
$mail->AddAddress("myaddress@gmail.com", "myname");
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "Here is the subject";
$mail->Body = "This is the HTML message body <b>in bold!</b>";
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
answered Jan 10, 2013 at 10:22
2
I encountered the same problem. To get it working, I had to go to myaccount.google.com -> «connected apps & sites», and turn «Allow less secure apps» to «ON» (near the bottom of the page).
Hope it helps some one
answered Aug 23, 2016 at 15:46
DeveloperDeveloper
3,7574 gold badges37 silver badges46 bronze badges
1
After signing up to appfog, I was able to get PHPMailer working with the following.
I was unable to find JPHPMailer, although I suspect that isn’t the cause of your issue but the fact that you were putting ssl://smtp.gmail.com as the host.
ini_set('display_errors', 1);
error_reporting(E_ALL);
include('class.phpmailer.php');
$mailer = new PHPMailer(true);
$mailer->IsSMTP();
$mailer->SMTPSecure = 'ssl';
$mailer->Host = 'smtp.gmail.com';
$mailer->Port = 465;
$mailer->SMTPAuth = true;
$mailer->Username = 'me@gmail.com';
$mailer->Password = 'password';
$mailer->SetFrom('me@gmail.com', 'Name');
$mailer->AddAddress('you@gmail.com');
$mailer->Subject = 'This is a test';
$mailer->Body = 'Test body';
$mailer->Send();
Hope this helps?
answered Jan 10, 2013 at 9:20
GavinGavin
6,2345 gold badges29 silver badges38 bronze badges
7
Print your PHPMailer
object and check PORT
on object and you given PORT
echo "<pre>", print_r($mailer, true);
exit;
answered Jan 30, 2016 at 4:26
UWU_SANDUNUWU_SANDUN
1,10513 silver badges19 bronze badges
3
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.
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»;
- WordPress Tutorials
- February 25, 2022
- 6 March 2022
Today, we are fixing a standard error in Gmail, which has caused problems for many of you. We try to answer the most common issues of WordPress users in various articles to get their answers faster. Most friends who use Gmail to send their email newsletters and connect to email marketing services face SMTP error: Could not authenticate.
The SMTP protocol is the interface between email and other applications that makes sending email easy. But sometimes, when you work with this protocol, you get errors that you have to fix. Here are some ways you can select one of them.
SMTP Error: Could not authenticate.
The Newsletter plugin is used to send newsletters on the website. You can send group emails to your website users through this plugin. This is a great way to grow your online business. You can easily promote your website without paying much money.
Therefore, due to the many features that Newsletter provides to its users, many users use it. To work well with this plugin, it is better to read the articles on the website about the Newsletter plugin.
Naturally, each plugin has its problems, and you should be able to fix them so that your website is not disrupted. SMTP Error: Could not authenticate is also one of the errors that may appear for you in the WordPress Newsletter plugin or any other plugins for various reasons.
There are several ways to fix this error, and here are three commonly used methods. So join us to fix this error, or if you encounter this error in the future, you can quickly fix it.
Now we want to see how to fix this error. Step by step, do the following:
Change your Gmail password to numbers
The first way we suggest you is to change your password. So first, it is better to change your Gmail password. When changing the password, use numbers to minimize the error when entering the password in the newsletter plugin.
Also, keep in mind that passwords are critical, and you need to be very careful when encrypting your Gmail that hackers can not access your Gmail. Here you have to use a simple password to resolve the error.
Disable Gmail 2-Step Login
Log in to Gmail with which you want to send newsletter emails and provide information to the system. Click on your avatar icon at the top right of the Gmail panel. Then click My Account.
Then click Sign In and Security.
Now find the 2 Step Verification option and click on it. Finally, click the Turn Off button to disable the two-step Gmail account login.
A two-step login of a Gmail account is an excellent and practical method that makes user accounts more secure. Google does this for its users to protect Google accounts. But here, it is better to do this to reduce the possibility of error.
Open access to low-security Gmail applications and sites
The third way we suggest you fix this error is to leave low-security apps and sites accessing your account. It would help if you did this to improve your mistake. Log in to your email again to do this. (This means the email you want to use in the Newsletter plugin.)
Now go to the settings page for low-security software.
And activate the button for this setting to turn blue.
Now your Newsletter plugin can send your emails without any problem.
But using these methods may not solve your problem. In this case, you need to contact your hosting provider. So if the emails are still not sent, ask your host to open ports 465 and 25 of your web server.
We hope you have been able to fix this error easily using this tutorial.
Be triumphant and victorious.
За последние 24 часа нас посетили 11532 программиста и 1149 роботов. Сейчас ищут 165 программистов …
-
- С нами с:
- 15 май 2018
- Сообщения:
- 10
- Симпатии:
- 0
Привет всем! Настраивал PHPMailer, но не получилось настроить его под gmail аккаунт, хотя c почты @mail.ru отправляет на отлично..
Ошибка — SMTP Error: Could not authenticate. ==> SMTP connect() failedВот мой код:
<?php//Namespace
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;//Require
require ‘PHPMailer/Exception.php’;
require ‘PHPMailer/PHPMailer.php’;
require ‘PHPMailer/SMTP.php’;//Mail
<?php//Namespace
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;//Require
require ‘PHPMailer/Exception.php’;
require ‘PHPMailer/PHPMailer.php’;
require ‘PHPMailer/SMTP.php’;//Mail
$mail = new PHPMailer();
$mail->CharSet = ‘UTF-8’;
$mail->isSMTP();
$mail->SMTPDebug = 4;
$mail->SMTPAuth = true;
$mail->SMTPSecure = «ssl»;
$mail->Host = «ssl://smtp.gmail.com»;
$mail->Port = 465;
$mail->Username = «*********@gmail.com»;
$mail->Password = «***************»;
$mail->SetFrom(‘schoolmavis@gmail.com’,’Mavis bot’);
$mail->AddAddress(«lis.lightinsky@gmail.com»);
$mail->Subject = «Test subject»;
$mail->Body = «English body»;
if(isset($_POST[‘send’]))
if (!$mail->Send())
{
echo «Error: $mail->ErrorInfo»;
}
else
{
echo «Message Sent!»;
}
?>
<form action method=»POST»>
<input type=»submit» value=»Send message» name=»send»>
</form>По-моему после отправки ($mail->send()) тупо срабатывает команда exit, и скрипт выходит, не показывая ничего ! (Если отключен SMTPDebug)
Логин, пароль от почты проверял не раз! В почте разрешено взаимодействие с другими приложениями и не стоит двойная аутентификация, поэтому там копать не стОит
Вложения:
-
Судя по логам, он все же коyнектится, но там ясно пишут — войдите через веб в почту.. возможно там будут какие то запросы, типа подтверждения почты, не ввел телефон или еще что
Было нечто подобное — не хотел через яндекс свежий ящик…. подставил старый — заработалону и — Password command failed: SMTP Error: Could not authenticate.
все же говорит что войти не смог -
- С нами с:
- 15 май 2018
- Сообщения:
- 10
- Симпатии:
- 0
ВНИМАНИЕ!!! Ооочень странный способ решения! Я добавил строчку $mail->SMTPKeepAlive = true и ВСЁ ЗАРАБОТАЛО! Сам бы в жизни не догадался
-
- С нами с:
- 26 фев 2012
- Сообщения:
- 2.176
- Симпатии:
- 180
За последние 24 часа нас посетили 9760 программистов и 785 роботов. Сейчас ищут 438 программистов …
-
VaneS
Активный пользователь- С нами с:
- 16 ноя 2011
- Сообщения:
- 631
- Симпатии:
- 3
- Адрес:
- Россия
Здравствуйте, у меня при отправке по SMTP выводится ошибка:
-
SMTP Error: Could not authenticate.
Как это исправить?
-
Команда форума
Модератор- С нами с:
- 15 мар 2007
- Сообщения:
- 9.901
- Симпатии:
- 968
правильно авторизоваться на smtp-сервере. русским по белому написано что? ошибка смтп: не смог аутентифицироваться
-
VaneS
Активный пользователь- С нами с:
- 16 ноя 2011
- Сообщения:
- 631
- Симпатии:
- 3
- Адрес:
- Россия
Почему с локального сервера все работает, а с удаленной VPS выдает эту ошибку? Ранее все работало, а на этой неделе просто перестал отправлять письма
-
Команда форума
Модератор- С нами с:
- 15 мар 2007
- Сообщения:
- 9.901
- Симпатии:
- 968
мб настройки смтп сменили?
-
VaneS
Активный пользователь- С нами с:
- 16 ноя 2011
- Сообщения:
- 631
- Симпатии:
- 3
- Адрес:
- Россия
Да в том и дело что ничего не меняли. Пытался подключаться к майлу и яндексу, ошибка оставалась прежняя, хотя ранее все работало нормально.
-
Предположение: у хостера обновили ssl, php-ssl — нет.
-
VaneS
Активный пользователь- С нами с:
- 16 ноя 2011
- Сообщения:
- 631
- Симпатии:
- 3
- Адрес:
- Россия
-
Попробуй поиграть с безопасностью транспорта:
$mail->SMTPSecure = ‘tls’;
или
$mail->SMTPSecure = ‘ssl’;Добавлено спустя 2 минуты 28 секунд:
я понимаю, но вы обновляли openSSL после небезызвестного бага?
-
Команда форума
Модератор- С нами с:
- 15 мар 2007
- Сообщения:
- 9.901
- Симпатии:
- 968
-
VaneS
Активный пользователь- С нами с:
- 16 ноя 2011
- Сообщения:
- 631
- Симпатии:
- 3
- Адрес:
- Россия
Кажется нет, а как это сделать?
Добавлено спустя 9 минут 53 секунды:
Моя CMS использует phpmailer, нашел там строку и заменил настройку, все заработало, спасибо большое!!!
Так все же, как обновить на сервере SSL? -
Команда форума
Модератор- С нами с:
- 15 мар 2007
- Сообщения:
- 9.901
- Симпатии:
- 968
руками из исходников скомпилировать. ну это если хорошо знаете что это. иначе дождитесь когда ментейнеры обновят rpm в репах центоса.
-
Там, чуть ли не в одних из первых появляется.
yum check-update
прочитает базу и выплюнет длинный список того, что давненько не обновлялось.
далее 2 пути:
1) обновить 1 openssl: yum update openssl
2) обновить все: yum update
I’m using PHPMailer in a Simple Script For Send Email’s Through Gmail, and I’m getting an «Unknown Error» (At least for me!):
SMTP Error: Could not authenticate.
Error: SMTP Error: Could not
authenticate.SMTP server error: 5.7.1 Username and
Password not accepted. Learn more at
535 5.7.1
http://mail.google.com/support/bin/answer.py?answer=14257
p38sm2467302ybk.16
I’ve read about Configure OpenSSL For SSL/TLS Connections, and I did it. Apache And PHP Are properly-Configured (With OpenSSL extension Running in PHP and mod_ssl running in Apache 2.2.16).
This is The PHP Script:
<?php
require_once ("PHPMailerclass.phpmailer.php");
$Correo = new PHPMailer();
$Correo->IsSMTP();
$Correo->SMTPAuth = true;
$Correo->SMTPSecure = "tls";
$Correo->Host = "smtp.gmail.com";
$Correo->Port = 587;
$Correo->UserName = "foo@gmail.com";
$Correo->Password = "gmailpassword";
$Correo->SetFrom('foo@gmail.com','De Yo');
$Correo->FromName = "From";
$Correo->AddAddress("bar@hotmail.com");
$Correo->Subject = "Prueba con PHPMailer";
$Correo->Body = "<H3>Bienvenido! Esto Funciona!</H3>";
$Correo->IsHTML (true);
if (!$Correo->Send())
{
echo "Error: $Correo->ErrorInfo";
}
else
{
echo "Message Sent!";
}
?>
The Username and Password are OK, And I tried in Thunderbird, without any problem.
I’ve also Used SSL Authentication and Port 465, getting the same Error.
Cœur
36.3k25 gold badges191 silver badges258 bronze badges
asked Oct 16, 2010 at 16:57
2
I encountered this problem. To get it working, I had to go to myaccount.google.com -> «Sign-in & security» -> «Apps with account access», and turn «Allow less secure apps» to «ON» (near the bottom of the page).
Alternatively you can follow this direct link to these settings
Joundill
6,41211 gold badges35 silver badges50 bronze badges
answered Sep 4, 2015 at 14:56
7
Try this instead :
$Correo->Username = «foo@gmail.com»;
I tested it and its working perfectly without no other change
answered Oct 16, 2010 at 17:19
malletjomalletjo
1,78616 silver badges18 bronze badges
2
I received the same error and in mycase it was the password. My password has special characters.
If you supply the password without escaping the special characters the error will persist.
E.g $mail->Password = " por$ch3";
is valid but will not work using the code above .
The solution should be as follows: $mail->Password = "por$ch3";
Note the Backslash I placed before the dollar character within my password.
That should work if you have a password using special characters
answered Aug 1, 2012 at 9:57
BubbaBubba
1011 silver badge7 bronze badges
2
I experienced the same error when configuring the WP-Mail-SMTP
plugin in WordPress.
The problem would persist even when I have ‘triple checked’ the settings and login credentials, and am able to log in manually using a browser.
There’s a list of steps you can take to fix this.
- Create a new password for the Gmail account you want to use
- Enable less secure apps in Google Security settings
- Use the
Display Unlock Captcha
page to give your app or website permission to sign in to Gmail. ClickContinue
or follow the instructions. - Sign in using the app or website. The smtp settings that work for me are 1) SMTP Host: smtp.gmail.com 2) SMTP port: 587 3) Encryption: TLS 4) Authentication: SMTP authentication 5) Username: example@gmail.com 6) Password: examplesecret
Greg
20.8k17 gold badges81 silver badges106 bronze badges
answered Jul 20, 2017 at 8:24
pyforkpyfork
3,5972 gold badges20 silver badges18 bronze badges
1
my solution is:
- change gmail password
- on gmail «Manage your google Account» > Security > Turn on 3rd party app Access
- This the new step that i discover by UnlockingCaptcha that told in this site, the exact site is https://accounts.google.com/b/0/DisplayUnlockCaptcha, but maybe you want to read the former site first.
That all, hope it works for you
answered Jul 15, 2020 at 15:37
1
Because Allow less secure apps is no longer available
The solution was to enable 2-step verification and generate app password
select mail and computer from the list then click generate
copy the code shown in the box and replace your google password with your app password it works like a charm.
answered Jun 28, 2022 at 2:10
Kym NTKym NT
6109 silver badges28 bronze badges
1
I received this error because of percentage signs in the password.
answered Dec 5, 2011 at 13:22
svandragtsvandragt
1,61320 silver badges37 bronze badges
1
For me I had a special characters in my password field, and I put it like $mail->Password = » por$ch3″ which work for gmail smpt server but not for other; so I just changed double quotes to single quotes and it works for me. $mail->Password = ‘ por$ch3’;
answered Jun 11, 2013 at 12:17
3
If you still face error in sending email, with the same error message. Try this:
$mail->SMTPSecure = 'tls';
$mail->Host = 'smtp.gmail.com';
just Before the line:
$send = $mail->Send();
or in other sense, before calling the Send() Function.
Tested and Working.
answered Jun 11, 2014 at 19:30
JackSparrowJackSparrow
9081 gold badge11 silver badges8 bronze badges
1
The other post is correct to resolve the issue but doesn’t address how to do it if the 2-step-verification is turned on. The option to allow the less secure apps is NOT available then. Here is an answer to how to do it:
a. Go to the URL of `https://myaccount.google.com/` and click `Sing-in and security`
b. Click on the app password.
You will reach a page like this,
c. Create name of your app and generate a password for the respective app.
d. Use that password acquired here inside the app.
This should resolve the issue.
answered May 20, 2018 at 10:16
ArefeArefe
10.4k16 gold badges101 silver badges159 bronze badges
0
I had the same issue and did all the tips including Gmail setting (e.g. less secure apps access) with no luck. But finally when I changed password to something different, for some reason it worked! FYI, the initial password did not have any special characters.
answered May 24, 2016 at 22:57
EhsanEhsan
1,02211 silver badges20 bronze badges
- first go to https://myaccount.google.com
- Select Security tab
- Scroll down and select ‘Less secure app access’
- Turn on access
This will solve my “SMTP Error: Could not authenticate” in PHPMailer error.
answered Apr 29, 2020 at 13:07
ruwanmadhusankaruwanmadhusanka
7812 gold badges7 silver badges15 bronze badges
I had the same issue and did all the tips with no luck. Finally when I changed password to something different, for some reason it worked! (the initial password or the new one did not have any special characters)
answered Aug 18, 2019 at 14:06
0
The correct answer:
Go to «Manage your google accounts => Security => Signing in to Google => App passwords».
Generate your maill account password there (that will be used from other device)
answered Apr 13, 2022 at 9:49
I had the same problem with authentication. The fix was to set up 2-step verification and create an application specific password for the device ( error messages for blocking the device will appear in your account settings->»Notifications and alerts» if you problem is the same with mine)
answered Jan 29, 2015 at 21:35
It was the selinux issue. I just updated the below given part in /etc/selinux/config file
SELINUX=permissive
(it was SELINUX=enforcing before).
then just reboot the system by giving
reboot
Now the mail goes without any hassle.
Configuration
From Email Address : [noreply@yourdomain.com]
From Name : [your domain name]
SMTP Host : smtp.gmail.com
Type of Encryption : SSL
SMTP Port : 465
SMTP Authentication : YES
Username : [your mail id]
Password : [your password]
answered Feb 10, 2016 at 7:17
SMTP Error: could not authenticate
I had the same problem. The following troubleshooting steps helped me.
- I turned off two-factor authentication in my gmail account.
- I allowed less secure apps to access my gmail account. To get it working, I had to go to
myaccount.google.com
->Sign-in & security
->Apps with account access
, and turnAllow less secure apps
toON
(near the bottom of the page). - At this step, when I tried to register a user, I would get the same error. Google would sent me a warning message that someone has my password and the login was blocked.
- Gmail will then provide you with options. You either click whether the activity was yours or not yours. Click the option that the activity was yours.
- Try registration again. It should now work.
cSteusloff
2,4376 gold badges27 silver badges50 bronze badges
answered Dec 14, 2017 at 11:47
There is no issue with your code.
Follow below two simple steps to send emails from phpmailer.
You have to disable 2-step verification setting for google account if you have enabled.
Turn ON allow access to less secure app.
answered Apr 12, 2018 at 7:24
I’m using PHPMailer in a Simple Script For Send Email’s Through Gmail, and I’m getting an «Unknown Error» (At least for me!):
SMTP Error: Could not authenticate.
Error: SMTP Error: Could not
authenticate.SMTP server error: 5.7.1 Username and
Password not accepted. Learn more at
535 5.7.1
http://mail.google.com/support/bin/answer.py?answer=14257
p38sm2467302ybk.16
I’ve read about Configure OpenSSL For SSL/TLS Connections, and I did it. Apache And PHP Are properly-Configured (With OpenSSL extension Running in PHP and mod_ssl running in Apache 2.2.16).
This is The PHP Script:
<?php
require_once ("PHPMailerclass.phpmailer.php");
$Correo = new PHPMailer();
$Correo->IsSMTP();
$Correo->SMTPAuth = true;
$Correo->SMTPSecure = "tls";
$Correo->Host = "smtp.gmail.com";
$Correo->Port = 587;
$Correo->UserName = "foo@gmail.com";
$Correo->Password = "gmailpassword";
$Correo->SetFrom('foo@gmail.com','De Yo');
$Correo->FromName = "From";
$Correo->AddAddress("bar@hotmail.com");
$Correo->Subject = "Prueba con PHPMailer";
$Correo->Body = "<H3>Bienvenido! Esto Funciona!</H3>";
$Correo->IsHTML (true);
if (!$Correo->Send())
{
echo "Error: $Correo->ErrorInfo";
}
else
{
echo "Message Sent!";
}
?>
The Username and Password are OK, And I tried in Thunderbird, without any problem.
I’ve also Used SSL Authentication and Port 465, getting the same Error.
Cœur
36.3k25 gold badges191 silver badges258 bronze badges
asked Oct 16, 2010 at 16:57
2
I encountered this problem. To get it working, I had to go to myaccount.google.com -> «Sign-in & security» -> «Apps with account access», and turn «Allow less secure apps» to «ON» (near the bottom of the page).
Alternatively you can follow this direct link to these settings
Joundill
6,41211 gold badges35 silver badges50 bronze badges
answered Sep 4, 2015 at 14:56
7
Try this instead :
$Correo->Username = «foo@gmail.com»;
I tested it and its working perfectly without no other change
answered Oct 16, 2010 at 17:19
malletjomalletjo
1,78616 silver badges18 bronze badges
2
I received the same error and in mycase it was the password. My password has special characters.
If you supply the password without escaping the special characters the error will persist.
E.g $mail->Password = " por$ch3";
is valid but will not work using the code above .
The solution should be as follows: $mail->Password = "por$ch3";
Note the Backslash I placed before the dollar character within my password.
That should work if you have a password using special characters
answered Aug 1, 2012 at 9:57
BubbaBubba
1011 silver badge7 bronze badges
2
I experienced the same error when configuring the WP-Mail-SMTP
plugin in WordPress.
The problem would persist even when I have ‘triple checked’ the settings and login credentials, and am able to log in manually using a browser.
There’s a list of steps you can take to fix this.
- Create a new password for the Gmail account you want to use
- Enable less secure apps in Google Security settings
- Use the
Display Unlock Captcha
page to give your app or website permission to sign in to Gmail. ClickContinue
or follow the instructions. - Sign in using the app or website. The smtp settings that work for me are 1) SMTP Host: smtp.gmail.com 2) SMTP port: 587 3) Encryption: TLS 4) Authentication: SMTP authentication 5) Username: example@gmail.com 6) Password: examplesecret
Greg
20.8k17 gold badges81 silver badges106 bronze badges
answered Jul 20, 2017 at 8:24
pyforkpyfork
3,5972 gold badges20 silver badges18 bronze badges
1
my solution is:
- change gmail password
- on gmail «Manage your google Account» > Security > Turn on 3rd party app Access
- This the new step that i discover by UnlockingCaptcha that told in this site, the exact site is https://accounts.google.com/b/0/DisplayUnlockCaptcha, but maybe you want to read the former site first.
That all, hope it works for you
answered Jul 15, 2020 at 15:37
1
Because Allow less secure apps is no longer available
The solution was to enable 2-step verification and generate app password
select mail and computer from the list then click generate
copy the code shown in the box and replace your google password with your app password it works like a charm.
answered Jun 28, 2022 at 2:10
Kym NTKym NT
6109 silver badges28 bronze badges
1
I received this error because of percentage signs in the password.
answered Dec 5, 2011 at 13:22
svandragtsvandragt
1,61320 silver badges37 bronze badges
1
For me I had a special characters in my password field, and I put it like $mail->Password = » por$ch3″ which work for gmail smpt server but not for other; so I just changed double quotes to single quotes and it works for me. $mail->Password = ‘ por$ch3’;
answered Jun 11, 2013 at 12:17
3
If you still face error in sending email, with the same error message. Try this:
$mail->SMTPSecure = 'tls';
$mail->Host = 'smtp.gmail.com';
just Before the line:
$send = $mail->Send();
or in other sense, before calling the Send() Function.
Tested and Working.
answered Jun 11, 2014 at 19:30
JackSparrowJackSparrow
9081 gold badge11 silver badges8 bronze badges
1
The other post is correct to resolve the issue but doesn’t address how to do it if the 2-step-verification is turned on. The option to allow the less secure apps is NOT available then. Here is an answer to how to do it:
a. Go to the URL of `https://myaccount.google.com/` and click `Sing-in and security`
b. Click on the app password.
You will reach a page like this,
c. Create name of your app and generate a password for the respective app.
d. Use that password acquired here inside the app.
This should resolve the issue.
answered May 20, 2018 at 10:16
ArefeArefe
10.4k16 gold badges101 silver badges159 bronze badges
0
I had the same issue and did all the tips including Gmail setting (e.g. less secure apps access) with no luck. But finally when I changed password to something different, for some reason it worked! FYI, the initial password did not have any special characters.
answered May 24, 2016 at 22:57
EhsanEhsan
1,02211 silver badges20 bronze badges
- first go to https://myaccount.google.com
- Select Security tab
- Scroll down and select ‘Less secure app access’
- Turn on access
This will solve my “SMTP Error: Could not authenticate” in PHPMailer error.
answered Apr 29, 2020 at 13:07
ruwanmadhusankaruwanmadhusanka
7812 gold badges7 silver badges15 bronze badges
I had the same issue and did all the tips with no luck. Finally when I changed password to something different, for some reason it worked! (the initial password or the new one did not have any special characters)
answered Aug 18, 2019 at 14:06
0
The correct answer:
Go to «Manage your google accounts => Security => Signing in to Google => App passwords».
Generate your maill account password there (that will be used from other device)
answered Apr 13, 2022 at 9:49
I had the same problem with authentication. The fix was to set up 2-step verification and create an application specific password for the device ( error messages for blocking the device will appear in your account settings->»Notifications and alerts» if you problem is the same with mine)
answered Jan 29, 2015 at 21:35
It was the selinux issue. I just updated the below given part in /etc/selinux/config file
SELINUX=permissive
(it was SELINUX=enforcing before).
then just reboot the system by giving
reboot
Now the mail goes without any hassle.
Configuration
From Email Address : [noreply@yourdomain.com]
From Name : [your domain name]
SMTP Host : smtp.gmail.com
Type of Encryption : SSL
SMTP Port : 465
SMTP Authentication : YES
Username : [your mail id]
Password : [your password]
answered Feb 10, 2016 at 7:17
SMTP Error: could not authenticate
I had the same problem. The following troubleshooting steps helped me.
- I turned off two-factor authentication in my gmail account.
- I allowed less secure apps to access my gmail account. To get it working, I had to go to
myaccount.google.com
->Sign-in & security
->Apps with account access
, and turnAllow less secure apps
toON
(near the bottom of the page). - At this step, when I tried to register a user, I would get the same error. Google would sent me a warning message that someone has my password and the login was blocked.
- Gmail will then provide you with options. You either click whether the activity was yours or not yours. Click the option that the activity was yours.
- Try registration again. It should now work.
cSteusloff
2,4376 gold badges27 silver badges50 bronze badges
answered Dec 14, 2017 at 11:47
There is no issue with your code.
Follow below two simple steps to send emails from phpmailer.
You have to disable 2-step verification setting for google account if you have enabled.
Turn ON allow access to less secure app.
answered Apr 12, 2018 at 7:24
I’m using PHPMailer in a Simple Script For Send Email’s Through Gmail, and I’m getting an «Unknown Error» (At least for me!):
SMTP Error: Could not authenticate.
Error: SMTP Error: Could not
authenticate.SMTP server error: 5.7.1 Username and
Password not accepted. Learn more at
535 5.7.1
http://mail.google.com/support/bin/answer.py?answer=14257
p38sm2467302ybk.16
I’ve read about Configure OpenSSL For SSL/TLS Connections, and I did it. Apache And PHP Are properly-Configured (With OpenSSL extension Running in PHP and mod_ssl running in Apache 2.2.16).
This is The PHP Script:
<?php
require_once ("PHPMailerclass.phpmailer.php");
$Correo = new PHPMailer();
$Correo->IsSMTP();
$Correo->SMTPAuth = true;
$Correo->SMTPSecure = "tls";
$Correo->Host = "smtp.gmail.com";
$Correo->Port = 587;
$Correo->UserName = "foo@gmail.com";
$Correo->Password = "gmailpassword";
$Correo->SetFrom('foo@gmail.com','De Yo');
$Correo->FromName = "From";
$Correo->AddAddress("bar@hotmail.com");
$Correo->Subject = "Prueba con PHPMailer";
$Correo->Body = "<H3>Bienvenido! Esto Funciona!</H3>";
$Correo->IsHTML (true);
if (!$Correo->Send())
{
echo "Error: $Correo->ErrorInfo";
}
else
{
echo "Message Sent!";
}
?>
The Username and Password are OK, And I tried in Thunderbird, without any problem.
I’ve also Used SSL Authentication and Port 465, getting the same Error.
Cœur
36.3k25 gold badges191 silver badges258 bronze badges
asked Oct 16, 2010 at 16:57
2
I encountered this problem. To get it working, I had to go to myaccount.google.com -> «Sign-in & security» -> «Apps with account access», and turn «Allow less secure apps» to «ON» (near the bottom of the page).
Alternatively you can follow this direct link to these settings
Joundill
6,41211 gold badges35 silver badges50 bronze badges
answered Sep 4, 2015 at 14:56
7
Try this instead :
$Correo->Username = «foo@gmail.com»;
I tested it and its working perfectly without no other change
answered Oct 16, 2010 at 17:19
malletjomalletjo
1,78616 silver badges18 bronze badges
2
I received the same error and in mycase it was the password. My password has special characters.
If you supply the password without escaping the special characters the error will persist.
E.g $mail->Password = " por$ch3";
is valid but will not work using the code above .
The solution should be as follows: $mail->Password = "por$ch3";
Note the Backslash I placed before the dollar character within my password.
That should work if you have a password using special characters
answered Aug 1, 2012 at 9:57
BubbaBubba
1011 silver badge7 bronze badges
2
I experienced the same error when configuring the WP-Mail-SMTP
plugin in WordPress.
The problem would persist even when I have ‘triple checked’ the settings and login credentials, and am able to log in manually using a browser.
There’s a list of steps you can take to fix this.
- Create a new password for the Gmail account you want to use
- Enable less secure apps in Google Security settings
- Use the
Display Unlock Captcha
page to give your app or website permission to sign in to Gmail. ClickContinue
or follow the instructions. - Sign in using the app or website. The smtp settings that work for me are 1) SMTP Host: smtp.gmail.com 2) SMTP port: 587 3) Encryption: TLS 4) Authentication: SMTP authentication 5) Username: example@gmail.com 6) Password: examplesecret
Greg
20.8k17 gold badges81 silver badges106 bronze badges
answered Jul 20, 2017 at 8:24
pyforkpyfork
3,5972 gold badges20 silver badges18 bronze badges
1
my solution is:
- change gmail password
- on gmail «Manage your google Account» > Security > Turn on 3rd party app Access
- This the new step that i discover by UnlockingCaptcha that told in this site, the exact site is https://accounts.google.com/b/0/DisplayUnlockCaptcha, but maybe you want to read the former site first.
That all, hope it works for you
answered Jul 15, 2020 at 15:37
1
Because Allow less secure apps is no longer available
The solution was to enable 2-step verification and generate app password
select mail and computer from the list then click generate
copy the code shown in the box and replace your google password with your app password it works like a charm.
answered Jun 28, 2022 at 2:10
Kym NTKym NT
6109 silver badges28 bronze badges
1
I received this error because of percentage signs in the password.
answered Dec 5, 2011 at 13:22
svandragtsvandragt
1,61320 silver badges37 bronze badges
1
For me I had a special characters in my password field, and I put it like $mail->Password = » por$ch3″ which work for gmail smpt server but not for other; so I just changed double quotes to single quotes and it works for me. $mail->Password = ‘ por$ch3’;
answered Jun 11, 2013 at 12:17
3
If you still face error in sending email, with the same error message. Try this:
$mail->SMTPSecure = 'tls';
$mail->Host = 'smtp.gmail.com';
just Before the line:
$send = $mail->Send();
or in other sense, before calling the Send() Function.
Tested and Working.
answered Jun 11, 2014 at 19:30
JackSparrowJackSparrow
9081 gold badge11 silver badges8 bronze badges
1
The other post is correct to resolve the issue but doesn’t address how to do it if the 2-step-verification is turned on. The option to allow the less secure apps is NOT available then. Here is an answer to how to do it:
a. Go to the URL of `https://myaccount.google.com/` and click `Sing-in and security`
b. Click on the app password.
You will reach a page like this,
c. Create name of your app and generate a password for the respective app.
d. Use that password acquired here inside the app.
This should resolve the issue.
answered May 20, 2018 at 10:16
ArefeArefe
10.4k16 gold badges101 silver badges159 bronze badges
0
I had the same issue and did all the tips including Gmail setting (e.g. less secure apps access) with no luck. But finally when I changed password to something different, for some reason it worked! FYI, the initial password did not have any special characters.
answered May 24, 2016 at 22:57
EhsanEhsan
1,02211 silver badges20 bronze badges
- first go to https://myaccount.google.com
- Select Security tab
- Scroll down and select ‘Less secure app access’
- Turn on access
This will solve my “SMTP Error: Could not authenticate” in PHPMailer error.
answered Apr 29, 2020 at 13:07
ruwanmadhusankaruwanmadhusanka
7812 gold badges7 silver badges15 bronze badges
I had the same issue and did all the tips with no luck. Finally when I changed password to something different, for some reason it worked! (the initial password or the new one did not have any special characters)
answered Aug 18, 2019 at 14:06
0
The correct answer:
Go to «Manage your google accounts => Security => Signing in to Google => App passwords».
Generate your maill account password there (that will be used from other device)
answered Apr 13, 2022 at 9:49
I had the same problem with authentication. The fix was to set up 2-step verification and create an application specific password for the device ( error messages for blocking the device will appear in your account settings->»Notifications and alerts» if you problem is the same with mine)
answered Jan 29, 2015 at 21:35
It was the selinux issue. I just updated the below given part in /etc/selinux/config file
SELINUX=permissive
(it was SELINUX=enforcing before).
then just reboot the system by giving
reboot
Now the mail goes without any hassle.
Configuration
From Email Address : [noreply@yourdomain.com]
From Name : [your domain name]
SMTP Host : smtp.gmail.com
Type of Encryption : SSL
SMTP Port : 465
SMTP Authentication : YES
Username : [your mail id]
Password : [your password]
answered Feb 10, 2016 at 7:17
SMTP Error: could not authenticate
I had the same problem. The following troubleshooting steps helped me.
- I turned off two-factor authentication in my gmail account.
- I allowed less secure apps to access my gmail account. To get it working, I had to go to
myaccount.google.com
->Sign-in & security
->Apps with account access
, and turnAllow less secure apps
toON
(near the bottom of the page). - At this step, when I tried to register a user, I would get the same error. Google would sent me a warning message that someone has my password and the login was blocked.
- Gmail will then provide you with options. You either click whether the activity was yours or not yours. Click the option that the activity was yours.
- Try registration again. It should now work.
cSteusloff
2,4376 gold badges27 silver badges50 bronze badges
answered Dec 14, 2017 at 11:47
There is no issue with your code.
Follow below two simple steps to send emails from phpmailer.
You have to disable 2-step verification setting for google account if you have enabled.
Turn ON allow access to less secure app.
answered Apr 12, 2018 at 7:24
0 Пользователей и 1 Гость просматривают эту тему.
- 6 Ответов
- 14021 Просмотров
Добрый день всем
у меня случилась грабля — отправляется почта но не на все ящики, точнее почти на все не отправляется, кроме некоторых моих.
раньше отправка была через php mail — на мои ящики приходило — а заказчик пишет что не может зарегиться — не приходит письмо
перепробовал все, Joomla 3.3
даже решил через smtp для яндекса — теперь выскакивает ошибка подключения
сейчас настройки для сервера следующие
отправка почты — Да
способ — smtp
email: имя@yandex.ru
отправитель: ИМЯ
авторизация: Да
защита: TLS
порт: 465
имя пользователя: имя
пароль: ***
server: smtp.yandex.ru
где то вскользь видел, что проблемы могут на стороне хостера — но не понимаю в чем они могут быть
не работает ни один способ отправки
хостер 1gb
нашел статейку, попробовал
Решение проблем связанных с отправкой почты в Joomla и VirtueMart
Самый простой способ отправки почты через функцию php mail, используйте этот способ отправки на вашем хостинге. Если вы в настройках указали способ отправки через php mail, а почта не отправляется, убедитесь, работает ли функция mail(). Для этого создайте в корне сайта файл test.php следующего содержания.
<?php
if (mail(«vasha_pachta@mail.ru», «Тема», «бла бла…nбла…бла….»))
echo ‘OK’;
else
echo ‘ERROR’;
?>
Запускаем файл: адрес_вашего_сайта/test.php, если после запуска скрипт выводит «ERROR», значит функция mail не работает на вашем сервере, стучите в техподдержку хостера, пускай подключают, все же 21 век на дворе). Если скрипт вывел «OK», значит письмо принято к отправке.
почта отправляется и приходит
значит mail() работает — там далее описано как править файл
После этого если письмо не дошло нужно подправить файл Joomla отвечающий за отправку почты. Открываем файл librariesphpmailerphpmailer.php находим примерно в 472 строке след. участок кода
1
$params = sprintf(«-oi -f %s», $this->Sender);
заменяем найденую строку на
1
2
$params = sprintf(«-oi -f %s», $this->Sender);
$params = «»;
В большинстве случаев проблема решается таким способом. Дело в том, что переменная $params используется в качестве 5го аргумента функции mail(), хотя обычно в функцию mail() достаточно передать 4 параметра. На некоторых хостингах почта из Joomla не отправляется с этим 5ым параметром.
если и после этого письма не отправляются значит они попадают в спам на стороне хостинга (возможно дело в адресе отправителя) либо на принимающей стороне (посмотрите в папке спам).
проблема в том что это описание для старой Joomla — в новой все подругому
причем самое паскудное, что регистрация через mail() приходит только на мои пару ящиков
вот это ваще мистика
то есть она ходит на мой gmail на мой mail
а на все остальные не ходит — эт ваще пипец какой то
мож конечно она работает через локальный комп на котором денвер стоит…
Дабы не создавать новые темы.спрошу здесь.Joomla стоит на локальном сервере.Настроил почту через Gmail. В настройках Gmail Установите переключатель Включить IMAP. Сделал.
В Joomla всё прописал по инструкции.При попытке отправить тестовое сообщение выводится ошибка. SMTP Error: Could not authenticate.
Помогите разобраться пожалуйста.
Чет долго никто не закроет вопрос. Один из ответов на эту тему SMTP Error: Could not authenticate нашел на сайте здесь
« Последнее редактирование: 12.11.2022, 20:47:06 от avtomastersu »
Записан
бред полнейший
если напрямую не указывать и не включать пароль приложений, то достаточно настроить порты
а smtp надо в почте ращрешить
Записан
индивидуальная помощь: @SetAlexx
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.
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.
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»;
Please check these things before submitting your issue:
- Make sure you’re using the latest version of PHPMailer
- Check that your problem is not dealt with in the troubleshooting guide, especially if you’re having problems connecting to Gmail or GoDaddy
- Include sufficient code to reproduce your problem
- If you’re having an SMTP issue, include the debug output generated with
SMTPDebug = 2
set - If you have a question about how to use PHPMailer (rather than reporting a bug in it), tag a question on Stack Overflow with
phpmailer
, but search first!
Problem description
When i trying send message from smtp.gmail.com, with ssl, or tls, or different ports, doesnt matter, it’s throw exception to me.
I have Allowed less secure apps in gmail, and i visit captcha confirmation
Code to reproduce
$mail->isSMTP(); $mail->SMTPDebug = 2; $mail->Host = "smtp.gmail.com"; $mail->SMTPAuth = true; $mail->SMTPSecure = "ssl"; $mail->Port = 465; $mail->CharSet = "UTF-8"; $mail->Username = "example@gmail.com"; $mail->Password = "*******"; $mail->setFrom("example@gmail.com", "Alex"); $mail->Subject = "Тест, отправка письма"; $mail->msgHTML("Message"); $mail->addAddress("example@mail.ru"); if (!$mail->send()) { $mail->ErrorInfo; } else { echo "123"; }
Debug output
2017-10-23 19:44:18 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP q24sm1694776lff.48 - gsmtp
2017-10-23 19:44:18 CLIENT -> SERVER: EHLO *my_server*
2017-10-23 19:44:18 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [*my_server*]250-SIZE 35882577250-8BITMIME250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2017-10-23 19:44:18 CLIENT -> SERVER: AUTH LOGIN
2017-10-23 19:44:18 SERVER -> CLIENT: 334 VXNlcm5hbWU6
2017-10-23 19:44:18 CLIENT -> SERVER: YXJldm9sdXRpb25wcm9qZWN0QGdtYWlsLmNvbQ==
2017-10-23 19:44:18 SERVER -> CLIENT: 334 UGFzc3dvcmQ6
2017-10-23 19:44:18 CLIENT -> SERVER: cmV2b2x1dGlvbjEyMw==
2017-10-23 19:44:18 SERVER -> CLIENT: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbtI534-5.7.14 qNIYrbZEk6FWx5rHcj6iG24Wnch4-cJAfM8uoUKM9jkHSMq_RaHs_A6dTS2Os70c6MUtaD534-5.7.14 5g_o5siaKUXvyrEugwt0FU-QBcUwp5HHAFfiHmTpuRu57eG1k4pH6sv5fXSQn2dgrZDEtn534-5.7.14 29ptACC7djB5Hv_usdmgN5yckn6u5Q79E3JqMGpS8nN7ZagN2geB2kO3-jkRJN8grPtIVK534-5.7.14 rAXLtSmpqVqRunISlK0V0x80FTYLY> Please log in via your web browser and534-5.7.14 then try again.534-5.7.14 Learn more at534 5.7.14 https://support.google.com/mail/answer/78754 q24sm1694776lff.48 - gsmtp
2017-10-23 19:44:18 SMTP ERROR: Password command failed: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbtI534-5.7.14 qNIYrbZEk6FWx5rHcj6iG24Wnch4-cJAfM8uoUKM9jkHSMq_RaHs_A6dTS2Os70c6MUtaD534-5.7.14 5g_o5siaKUXvyrEugwt0FU-QBcUwp5HHAFfiHmTpuRu57eG1k4pH6sv5fXSQn2dgrZDEtn534-5.7.14 29ptACC7djB5Hv_usdmgN5yckn6u5Q79E3JqMGpS8nN7ZagN2geB2kO3-jkRJN8grPtIVK534-5.7.14 rAXLtSmpqVqRunISlK0V0x80FTYLY> Please log in via your web browser and534-5.7.14 then try again.534-5.7.14 Learn more at534 5.7.14 https://support.google.com/mail/answer/78754 q24sm1694776lff.48 - gsmtp
SMTP Error: Could not authenticate.
2017-10-23 19:44:18 CLIENT -> SERVER: QUIT
2017-10-23 19:44:19 SERVER -> CLIENT: 221 2.0.0 closing connection q24sm1694776lff.48 - gsmtp
SMTP Error: Could not authenticate.
How to Solve SMTP: Could Not Authenticate using Gmail + PHPMailer?
December 23, 2019
email smtp, gmail, php
Sending a mail through PHPMailer is often scripted via PHP if you intend to send email notifications when new comments are recieved on your wordpress blog, or when the server is overloaded with high CPU spikes (via uptime showing load-averages in the last 1, 5 and 15 minutes).
If you are using Gmail, most likely is that the Google GMail will report back with a error: Could Not Authenticate even you have typed in the correct password for your Gmail account.
Putting your account password directly somewhere in your script is not a good idea, and the correct way to solve this problem and avoid leaking your main account password is to use the App Password. Alternatively, you can customize your security settings for less-secured applications – which it may not work as it is just a PHP script here.
App Password can be set separately for each individual application and you can also re-generate one if one is compromised.
You would need to visit Google Security Dashboard: https://myaccount.google.com/security
google-app-passwords-security
Then, add a App Password (Select GMail, and Others – give the App a Name) – which can be used in the PHPMailer – in case this password is leaked, you can always delete it and regenerate a new one.
google-app-passwords
Then, the following PHPMailer sample code should be used to do the email testing.
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 30 31 32 33 34 35 36 37 38 39 40 |
#!/usr/bin/php <?php use PHPMailerPHPMailerPHPMailer; use PHPMailerPHPMailerException; require 'PHPMailer/src/Exception.php'; require 'PHPMailer/src/PHPMailer.php'; require 'PHPMailer/src/SMTP.php'; $host = "smtp.gmail.com"; $port = 587; $secure = "tls"; // or the following configurations through SSL should work as well. // $port = 465; // $secure = "ssl"; $username = "Your GMAIL email"; $password = "Your GMAIL App Password"; try { $mailer = new PHPMailer(true); $mailer->IsHTML(true); $mailer->IsSMTP(); $mailer->From = $username; $mailer->FromName = $username; $mailer->ClearAllRecipients(); $mailer->AddAddress("Recipent Email Address", "Recipent"); $mailer->Subject = "Subject "; $mailer->Body = "Hello, time is: ". date("Y-m-d h:i:s"); $mailer->SMTPAuth = true; // enable SMTP authentication $mailer->SMTPSecure = $secure; // sets the prefix to the servier $mailer->Host = $host; // sets GMAIL as the SMTP server $mailer->Port = $port; // set the SMTP port for the GMAIL server $mailer->Username = $username; // GMAIL username $mailer->Password = $password; // GMAIL password $result = $mailer->Send(); echo "Mail sentn"; } catch (Exception $e) { echo 'Message could not be sent. Mailer Error: '; var_dump($e); } |
#!/usr/bin/php <?php use PHPMailerPHPMailerPHPMailer; use PHPMailerPHPMailerException; require 'PHPMailer/src/Exception.php'; require 'PHPMailer/src/PHPMailer.php'; require 'PHPMailer/src/SMTP.php'; $host = "smtp.gmail.com"; $port = 587; $secure = "tls"; // or the following configurations through SSL should work as well. // $port = 465; // $secure = "ssl"; $username = "Your GMAIL email"; $password = "Your GMAIL App Password"; try { $mailer = new PHPMailer(true); $mailer->IsHTML(true); $mailer->IsSMTP(); $mailer->From = $username; $mailer->FromName = $username; $mailer->ClearAllRecipients(); $mailer->AddAddress("Recipent Email Address", "Recipent"); $mailer->Subject = "Subject "; $mailer->Body = "Hello, time is: ". date("Y-m-d h:i:s"); $mailer->SMTPAuth = true; // enable SMTP authentication $mailer->SMTPSecure = $secure; // sets the prefix to the servier $mailer->Host = $host; // sets GMAIL as the SMTP server $mailer->Port = $port; // set the SMTP port for the GMAIL server $mailer->Username = $username; // GMAIL username $mailer->Password = $password; // GMAIL password $result = $mailer->Send(); echo "Mail sentn"; } catch (Exception $e) { echo 'Message could not be sent. Mailer Error: '; var_dump($e); }
Remember, you would also need to update the Email settings in WordPress Plugin – SMTP. And make sure you have the following credentials for Gmail updated in the wp-settings.php
1 2 |
define( 'WPMS_ON', true ); define( 'WPMS_SMTP_PASS', 'You GMAIL App Password' ); |
define( 'WPMS_ON', true ); define( 'WPMS_SMTP_PASS', 'You GMAIL App Password' );
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading…
589 words
Last Post: The Reduce Function in Python
Next Post: Find Numbers with Even Number of Digits using the Reduce Function in Javascript, C++ and Python
The Permanent URL is: How to Solve SMTP: Could Not Authenticate using Gmail + PHPMailer? (AMP Version)
dainis12 0 / 0 / 0 Регистрация: 20.03.2018 Сообщений: 27 |
||||
1 |
||||
14.04.2018, 20:57. Показов 9426. Ответов 11 Метки нет (Все метки)
Вот код
Подскажите пожалуйста в чем может быть проблема
__________________
0 |
Jodah 3802 / 3160 / 1326 Регистрация: 01.08.2012 Сообщений: 10,717 |
||||
14.04.2018, 21:31 |
2 |
|||
И смотрите выведенные логи.
0 |
0 / 0 / 0 Регистрация: 20.03.2018 Сообщений: 27 |
|
14.04.2018, 21:40 [ТС] |
3 |
Хм хм, как бы спросить что это все означает и при этом не раскрыть данные… Добавлено через 3 минуты по ссылке для справки пишет: страница не найдена! Добавлено через 1 минуту
0 |
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 |
3802 / 3160 / 1326 Регистрация: 01.08.2012 Сообщений: 10,717 |
|
15.04.2018, 13:45 |
6 |
Но для этого нужен аккаунт в G Suite Не знаю, что это. Доступ по IMAP включается в настройках в веб-интерфейсе почты.
0 |
0 / 0 / 0 Регистрация: 20.03.2018 Сообщений: 27 |
|
15.04.2018, 13:51 [ТС] |
7 |
Включение доступа по протоколам POP и IMAP Войдите в Консоль администратора Google. Войдите в аккаунт администратора (ваш текущий аккаунт …@gmail.com не подходит). Совет. Ссылка на раздел «Расширенные настройки» находится в самом низу страницы Gmail. Это написано в https://support.google.com/a/answer/105694?hl=ru
0 |
3802 / 3160 / 1326 Регистрация: 01.08.2012 Сообщений: 10,717 |
|
15.04.2018, 14:21 |
8 |
dainis12, так в заголовке написано, что речь идёт как раз про G Suite, это не ваш случай. Месяца 3 назад подключал гуглопочту. Если не ошибаюсь, нужно было сделать всего 2 вещи: Может быть что-то упустил, но с 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 /**
Вот такой код находится в этом файле! Однако как раз строчка 212 пустая, но вот уже на 215 появляется переменная var в которой вроде как хранится пароль, пароль действительно у меня состоял только из одних цифр, однако я его поменял на буквенный, перезапустил сервер и пару раз обновил, но ошибка осталась! Добавлено через 58 секунд Добавлено через 3 минуты
0 |
91 / 91 / 13 Регистрация: 14.07.2012 Сообщений: 539 |
|
15.04.2018, 21:35 |
10 |
dainis12, зачем Вы в коде ковыряетесь? Там все работает. Смотрите хелп по майлеру, там написанно как работать с гмайлом. У него свои приколы.
0 |
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 Ошибка в php скрипте: Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING Ошибка: FATAL ERROR Uncaught Error: Call to undefined function Test() В чем ошибка (Parse error: syntax error, unexpected ‘$i’ (T_VARIABLE), expecting ‘;’) ? Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 12 |