Answer the question
In order to leave comments, you need to log in
PHP. PhpMailer how to send SMTP mail via gmail.com from google? Why authorization error?
I'm trying to send mail via SMTP via Google Gmail.com using PhpMailer in PHP language. For some reason, an authorization error occurs. Although through Yandex, Mile and HotMail from Microsoft it is normally sent.
I am using the following code
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require "vendor/autoload.php";
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";//Сервер SMTP gmail
$mail->SMTPAuth = true;
$mail->Username = "[email protected]";//В документации Google указано что логин это адрес вместе с собакой
$mail->Password = "password";//Пароль
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;//Указываем что TLS
$mail->Port = 587;
$mail->setFrom("[email protected]","От кого отправляю");
$mail->addAddress("[email protected]","");//Кому отправляем письмо
$mail->isHTML(true);//Письмо в формате HTML
$mail->Subject = "Тема сообщения";
$mail->Body = "Содержание сообщения";
$mail->AltBody = "Альтернативное содержание сообщения";
$mail->send();
echo 'Сообщение отправлено';
} catch (Exception $e) {
echo "Ошибка отправки: {$mail->ErrorInfo}";
}
Answer the question
In order to leave comments, you need to log in
I did the following, the wisgest user suggested switching the flag of unsafe applications using the link https://myaccount.google.com/lesssecureapps, it was turned off for me, it didn’t help right away.
Then I removed the line from the code (commented it out): $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
added this $mail->SMTPSecure = 'tls';
Here is the final code with which I sent:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'password';
$mail->Port = 587;
$mail->setFrom("[email protected]","Имя от кого отправлять");
$mail->addAddress("[email protected]","");//Кому отправляем
//$mail->addReplyTo("[email protected]","Имя кому писать при ответе");
$mail->SMTPSecure = 'tls';
$mail->isHTML(true);//HTML формат
$mail->Subject = "Тема сообщения";
$mail->Body = "Содержание сообщения";
$mail->AltBody = "Альтернативное содержание сообщения";
$mail->send();
echo "Сообщение отправлено";
} catch (Exception $e) {
echo "Ошибка отправки: {$mail->ErrorInfo}";
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question