Меню

Ошибка expected response code 220 but got an empty response

enter image description hereI am following a tutorial to build an API using passport authentication on enter link description here
I have followed the part 1 and walking through the part 2 with account confirmation and notifications but eventually got a problem when I am testing on POSTMAN. The issue is, it does add to the database only that there is no mail sent with the error. I don’t know of there is any configuration I need to do in .env or mail.php. As I tried to configure the email address, STMP and password. The same error is displayed again and most issues I have seen on here are quite different as most are pertaining to mail.php and .env which I have no idea as there is no such on the tutorial link and I even tried to alter the mail.php and .env, I ran php artisan cache:clear but the same error is displayed.

<?php

namespace AppNotifications;

use IlluminateBusQueueable;
use IlluminateNotificationsNotification;
use IlluminateContractsQueueShouldQueue;
use IlluminateNotificationsMessagesMailMessage;

class SignupActivate extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return IlluminateNotificationsMessagesMailMessage
     */
    public function toMail($notifiable)
{
    $url = url('/api/auth/signup/activate/'.$notifiable->activation_token);
    return (new MailMessage)
        ->subject('Confirm your account')
        ->line('Thanks for signup! Please before you begin, you must confirm your account.')
        ->action('Confirm Account', url($url))
        ->line('Thank you for using our application!');
}
    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

I did also, two ways authentication
Mail.php

<?php

return [

 
    'driver' => env('MAIL_DRIVER', 'smtp'),

    'host' => env('MAIL_HOST', 'smtp.gmail.com'),

    'port' => env('MAIL_PORT', 587),

    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'username@gmail.com'),
        'name' => env('MAIL_FROM_NAME', 'Payne Curtis'),
    ],

    'encryption' => env('MAIL_ENCRYPTION', 'tls'),

    'username' => env('MAIL_USERNAME'),

    'password' => env('MAIL_PASSWORD'),


    'sendmail' => '/usr/sbin/sendmail -bs',

    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

    'log_channel' => env('MAIL_LOG_CHANNEL'),

];

.env

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=username@gmail.com
MAIL_PASSWORD=XXXXXXXXXXXXXXX
MAIL_ENCRYPTION=null

Q A
Bug report? no
Feature request? no
RFC? no
How used? Symfony
Swiftmailer version 6.2.1
PHP version 7.3.14

Observed behaviour

I use Swiftmailer in Laravel to send messages to a mailgun server. It worked fine for the last 6 months, but lately I’ve been encountering errors regarding an empty response. Googling returns answers to what I think is a similar problem («Expected response code 220 but got code «», with message «) but as the message is not the same, I don’t know if it’s the exact same error and the solutions don’t help me. As far as I know Laravel is using TLS as I haven’t changed that setting.
I can’t replicate the error, we send almost 100 mails daily and just a few return this error. Haven’t figured out what fails.

Expected behaviour

The mail should be consistent in succeeding or failing, but it only occurs sometimes.

Example

Can’t reproduce.

Logs

Attached an example log
laravel-2020-04-06.log

Is the problem related to my coding, my mail provider or is it just the package? The problem is happening on a server in production so I don’t want to update just for the sake of it.

We had the same problem. My hoster found the solution. It was the old version of SwiftMailer.

The error we got was:
 

SymfonyComponentDebugExceptionUndefinedMethodException:
Attempted to call an undefined method named "newInstance" of class "Swift_SmtpTransport".

at override/classes/Mail.php:714
at MailCore::sendMailTest('1', 'mail.agenturserver.de', 'Dies ist eine Test-Mail. Ihr Server kann nun E-Mails versenden.', 'Test-Nachricht -- PrestaShop', 'text/html', '[Email-Adress]', '[Email-Adress]', '[User-Name]', '[Password]', '465', 'ssl')
(src/Adapter/Email/EmailConfigurationTester.php:99)
at PrestaShopPrestaShopAdapterEmailEmailConfigurationTester->testConfiguration(array('send_email_to' => '[Email-Adress]', 'mail_method' => '2', 'smtp_server' => 'mail.agenturserver.de', 'smtp_username' => '[Username]', 'smtp_password' => null, 'smtp_port' => '465', 'smtp_encryption' => 'ssl'))
(src/PrestaShopBundle/Controller/Admin/Configure/AdvancedParameters/EmailController.php:261)
at PrestaShopBundleControllerAdminConfigureAdvancedParametersEmailController->sendTestAction(object(Request))
(vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php:151)
at SymfonyComponentHttpKernelHttpKernel->handleRaw(object(Request), 1)
(vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php:68)
at SymfonyComponentHttpKernelHttpKernel->handle(object(Request), 1, false)
(vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php:200)
at SymfonyComponentHttpKernelKernel->handle(object(Request), 1, false)
(admin/index.php:82)

We changed following things in the file /overrides/classes/Mail.php:

Old:
##

709 try {
710 if ($smtpChecked) {
711 if (Tools::strtolower($smtpEncryption) === 'off') {
712 $smtpEncryption = false;
713 }
714 $smtp = Swift_SmtpTransport::newInstance($smtp_server, $smtpPort, $smtpEncryption)
715 ->setUsername($smtpLogin)
716 ->setPassword($smtpPassword);
717 $swift = Swift_Mailer::newInstance($smtp);
718 } else {
719 $swift = Swift_Mailer::newInstance(Swift_MailTransport::newInstance());
720 }
721
722 $message = Swift_Message::newInstance();
723
724 $message
725 ->setFrom($from)
726 ->setTo($to)
727 ->setSubject($subject)
728 ->setBody($content);
729
730 if ($swift->send($message)) {
731 $result = true;
732 }
733 } catch (Swift_SwiftException $e) {
734 $result = $e->getMessage();
735 }
736
737 return $result;
738 }

##

New:

##

709 try {
710 if ($smtpChecked) {
711 if (Tools::strtolower($smtpEncryption) === 'off') {
712 $smtpEncryption = false;
713 }
714 $smtp = new Swift_SmtpTransport($smtp_server, $smtpPort, $smtpEncryption);
715 $smtp
716 ->setUsername($smtpLogin)
717 ->setPassword($smtpPassword);
718 $swift = new Swift_Mailer($smtp);
719 } else {
720 $swift = new Swift_Mailer(new Swift_MailTransport());
721 }
722
723 $message = new Swift_Message();
724
725 $message
726 ->setFrom($from)
727 ->setTo($to)
728 ->setSubject($subject)
729 ->setBody($content);
730
731 if ($swift->send($message)) {
732 $result = true;
733 }
734 } catch (Swift_SwiftException $e) {
735 $result = $e->getMessage();
736 }
737
738 return $result;
739 }

##

The reason for this error is, ::newInstance doesn´t work anymore in PHP.

Hope, this helps you all!

Для теста настроил в системе программу ssmtp, чтобы проверить как будет уходить почта через почтовый сервер yandex.ru. Настройки следующие:

root=***@yandex.ru
mailhub=smtp.yandex.ru:465
rewriteDomain=yandex.ru
hostname=yandex.ru
AuthUser=***
AuthPass=***
UseTLS=YES

И с этими настройками почта отправляется.

Теперь пробую использовать такие же настройки в Laravel. В файле .env прописано:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.yandex.ru
MAIL_PORT=465
MAIL_USERNAME=***
MAIL_PASSWORD=***
MAIL_ENCRYPTION=tls

Однако, при отправке почты происходит ошибка:

Swift_TransportException
Connection to tcp://smtp.yandex.ru:465 Timed Out

Я пробовал другие комбинации порта и шифрования, но они тоже не работают:

465, ssl:
Swift_TransportException (553)
Expected response code 250 but got code "553", with message "553 5.7.1 Sender address rejected: not owned by auth user. "

587, ssl:
Swift_TransportException
Connection could not be established with host smtp.yandex.ru [ #0]

587, tls:
Swift_TransportException (553)
Expected response code 250 but got code "553", with message "553 5.7.1 Sender address rejected: not owned by auth user. "

Вопрос. Как заставить работать почту в Laravel через smtp?

UPD: Еще я пробовал поставить такую настройку:

Все остальные значения MAIL_* приравнял null. Сделал я это
в надежде, что стработает PHP-шная функция mail(), которая у меня работает с помощью настроенного ssmtp. Например, такой код работает:

<?php 
mail("sample@gmail.com", "Отправка через SSMTP агента", "Это проверка отправки"); 
?>

Но после этой настройки и сброса кеша настроек:

$ ./artisan config:cache
Configuration cache cleared!
Configuration cached successfully!

Попытка отправки почты завершается ошибкой:

Swift_TransportException
Expected response code 220 but got an empty response

Example: swift_transportexception expected response code 220 but got an empty response

This problem can generally occur when you do not enable two step verification for the gmail account (which can be done here) you are using to send an email. So first, enable two step verification, you can find plenty of resources for enabling two step verification. After you enable it, then you have to create an app password. And use the app password in your .env file. When you are done with it, your .env file will look something like.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=<<your email address>>
MAIL_PASSWORD=<<app password>>
MAIL_ENCRYPTION=tls
and your mail.php

<?php

return [
    'driver' => env('MAIL_DRIVER', 'smtp'),
    'host' => env('MAIL_HOST', 'smtp.gmail.com'),
    'port' => env('MAIL_PORT', 587),
    'from' => ['address' => '<<your email>>', 'name' => '<<any name>>'],
    'encryption' => env('MAIL_ENCRYPTION', 'tls'),
    'username' => env('MAIL_USERNAME'),
    'password' => env('MAIL_PASSWORD'),
    'sendmail' => '/usr/sbin/sendmail -bs',
    'pretend' => false,

];
After doing so, run php artisan config:cache and php artisan config:clear, then check, email should work.

Tags:

Misc Example

Related


0

1

Для теста настроил в системе программу ssmtp, чтобы проверить как будет уходить почта через почтовый сервер yandex.ru. Настройки следующие:

root=***@yandex.ru
mailhub=smtp.yandex.ru:465
rewriteDomain=yandex.ru
hostname=yandex.ru
AuthUser=***
AuthPass=***
UseTLS=YES

И с этими настройками почта отправляется.

Теперь пробую использовать такие же настройки в Laravel. В файле .env прописано:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.yandex.ru
MAIL_PORT=465
MAIL_USERNAME=***
MAIL_PASSWORD=***
MAIL_ENCRYPTION=tls

Однако, при отправке почты происходит ошибка:

Swift_TransportException
Connection to tcp://smtp.yandex.ru:465 Timed Out

Я пробовал другие комбинации порта и шифрования, но они тоже не работают:

465, ssl:
Swift_TransportException (553)
Expected response code 250 but got code "553", with message "553 5.7.1 Sender address rejected: not owned by auth user. "

587, ssl:
Swift_TransportException
Connection could not be established with host smtp.yandex.ru [ #0]

587, tls:
Swift_TransportException (553)
Expected response code 250 but got code "553", with message "553 5.7.1 Sender address rejected: not owned by auth user. "

Вопрос. Как заставить работать почту в Laravel через smtp?

UPD: Еще я пробовал поставить такую настройку:

Все остальные значения MAIL_* приравнял null. Сделал я это
в надежде, что стработает PHP-шная функция mail(), которая у меня работает с помощью настроенного ssmtp. Например, такой код работает:

<?php 
mail("sample@gmail.com", "Отправка через SSMTP агента", "Это проверка отправки"); 
?>

Но после этой настройки и сброса кеша настроек:

$ ./artisan config:cache
Configuration cache cleared!
Configuration cached successfully!

Попытка отправки почты завершается ошибкой:

Swift_TransportException
Expected response code 220 but got an empty response

За последние 24 часа нас посетили 8872 программиста и 815 роботов. Сейчас ищут 376 программистов …

Отправка писем из Laravel с помощью SMTP через yandex.ru

Тема в разделе «Laravel», создана пользователем xintrea, 3 апр 2019.


  1. xintrea

    xintrea
    Активный пользователь

    С нами с:
    25 фев 2019
    Сообщения:
    68
    Симпатии:
    0

    Для теста настроил в системе программу ssmtp, чтобы проверить как будет уходить почта через почтовый сервер yandex.ru. Настройки следующие:

    1. mailhub=smtp.yandex.ru:465

    И с этими настройками почта отправляется.

    Теперь пробую использовать такие же настройки в Laravel. В файле .env прописано:

    Однако, при отправке почты происходит ошибка:

    1. Connection to tcp://smtp.yandex.ru:465 Timed Out

    Я пробовал другие комбинации порта и шифрования, но они тоже не работают:

    1. Swift_TransportException (553)
    2. Expected response code 250 but got code «553», with message «553 5.7.1 Sender address rejected: not owned by auth user. «
    3. Connection could not be established with host smtp.yandex.ru [ #0]
    4. Swift_TransportException (553)
    5. Expected response code 250 but got code «553», with message «553 5.7.1 Sender address rejected: not owned by auth user. «

    Вопрос. Как заставить работать почту в Laravel через smtp?

    UPD: Еще я пробовал поставить такую настройку:

    Все остальные значения MAIL_* приравнял null. Сделал я это
    в надежде, что стработает PHP-шная функция mail(), которая у меня работает с помощью настроенного ssmtp. Например, такой код работает:

    1. mail(«sample@gmail.com», «Отправка через SSMTP агента», «Это проверка отправки»);

    Но после этой настройки и сброса кеша настроек:

    1. Configuration cache cleared!
    2. Configuration cached successfully!

    Попытка отправки почты завершается ошибкой:

    1. Expected response code 220 but got an empty response

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка esp ниссан навара
  • Ошибка expected primary expression before token