Не удалось установить соединение с хостом mailtrap.io [php_network_getaddresses: getaddrinfo failed: такой хост не известен. # 0]

Я получаю сообщение об ошибке ниже:

Не удалось установить соединение с хостом smtp.gmail.com [php_network_getaddresses: getaddrinfo failed: такой хост не известен.

0]

Мой файл .env выглядит так:

MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=xxxxxxxxxxxxxx
MAIL_PASSWORD=xxxxxxxx
#MAIL_ENCRYPTION=null

Мой файл mail.php внутри конфигурации выглядит так:

/*
    |--------------------------------------------------------------------------
    | Mail Driver
    |--------------------------------------------------------------------------
    |
    | Laravel supports both SMTP and PHP's "mail" function as drivers for the
    | sending of e-mail. You may specify which one you're using throughout
    | your application here. By default, Laravel is setup for SMTP mail.
    |
    | Supported: "smtp", "mail", "sendmail", "mailgun", "mandrill",
    |            "ses", "sparkpost", "log"
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Address
    |--------------------------------------------------------------------------
    |
    | Here you may provide the host address of the SMTP server used by your
    | applications. A default option is provided that is compatible with
    | the Mailgun mail service which will provide reliable deliveries.
    |
    */

    'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Port
    |--------------------------------------------------------------------------
    |
    | This is the SMTP port used by your application to deliver e-mails to
    | users of the application. Like the host we have set this value to
    | stay compatible with the Mailgun e-mail application by default.
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | Global "From" Address
    |--------------------------------------------------------------------------
    |
    | You may wish for all e-mails sent by your application to be sent from
    | the same address. Here, you may specify a name and address that is
    | used globally for all e-mails that are sent by your application.
    |
    */

    'from' => ['address' => null, 'name' => null],

    /*
    |--------------------------------------------------------------------------
    | E-Mail Encryption Protocol
    |--------------------------------------------------------------------------
    |
    | Here you may specify the encryption protocol that should be used when
    | the application send e-mail messages. A sensible default using the
    | transport layer security protocol should provide great security.
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | SMTP Server Username
    |--------------------------------------------------------------------------
    |
    | If your SMTP server requires a username for authentication, you should
    | set it here. This will get used to authenticate with your server on
    | connection. You may also set the "password" value below this one.
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | SMTP Server Password
    |--------------------------------------------------------------------------
    |
    | Here you may set the password required by your SMTP server to send out
    | messages from your application. This will be given to the server on
    | connection so that the application will be able to send messages.
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | Sendmail System Path
    |--------------------------------------------------------------------------
    |
    | When using the "sendmail" driver to send e-mails, we will need to know
    | the path to where Sendmail lives on this server. A default path has
    | been provided here, which will work well on most of your systems.
    |
    */

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

];

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

Любые предложения будут очень признательны.


person Alwaysalearner    schedule 17.01.2017    source источник
comment
вы не указали учетные данные для почты в файле .env, все установлено равным нулю   -  person Niklesh Raut    schedule 17.01.2017
comment
зарегистрируйтесь на https://mailtrap.io и получите имя пользователя / пароль, как указано здесь: code.tutsplus.com/tutorials/   -  person Niklesh Raut    schedule 17.01.2017
comment
@Rishi, я обновил свой вопрос. Сейчас я использую другие детали.   -  person Alwaysalearner    schedule 17.01.2017
comment
в вашем .env файле добавьте следующий код и попробуйте еще раз MAIL_DRIVER = smtp MAIL_ENCRYPTION = tls   -  person Hanif Formoly    schedule 12.07.2017
comment
нам нужно сначала связаться с провайдером хостинга или домена и зарегистрировать домен. Нам нужно зарегистрировать запись A и запись MX для mail.yourdomain.com. Команда хостинга проведет вас через процесс. После регистрации домена вам нужно подождать от 4 до 8 часов, чтобы он отразился.   -  person Reejesh PK    schedule 10.06.2020


Ответы (9)


Эта проблема возникает, если в файлы были внесены некоторые изменения, в частности, в файл .env.

Очистить кеш с помощью команды artisan

php artisan cache:clear

Очистить конфигурацию

php artisan config:clear

Перезагрузите ваш сервер

sudo service apache2 restart

Подробнее: попробуйте очистить кеш и файлы cookie браузера. Надеюсь, что это сработает

person Yogesh Nogia    schedule 30.03.2018
comment
Почему я не подумал об этом ?! - person DavidHyogo; 18.12.2018
comment
Это сработало для меня с той же проблемой - я хотел бы понять, почему это работает - это решило мою проблему, но я не понимаю, почему. - person Mhluzi Bhaka; 04.05.2021
comment
На самом деле это похоже на временное решение - проблема вернулась ко мне. - person Mhluzi Bhaka; 05.05.2021

У меня была такая же проблема.

Похоже, что сервер не может проверить связь с адресом назначения.

Я быстро перезапустил свой сервер разработки, и все вернулось в норму.

Надеюсь, это поможет.

person Ferdie De Oliveira    schedule 22.03.2017
comment
У меня была эта проблема, когда я использовал кнопку забытого пароля (laravel breeze auth). можешь мне помочь? - person Daisy; 30.04.2021

Используйте приведенный ниже код в .env файле:

MAIL_ENCRYPTION= TLS

Попробуйте очистить cache, config cache и restart apache2.

Оно работает.

person Pravin    schedule 15.05.2018
comment
Спасибо за подсказку. У меня это сработало. Хотя перезапуск apache2 не требуется. Кажется, Laravel 5.6.35 достаточно умен, чтобы знать об изменениях. - person forethought; 02.09.2018

Проблема на самом деле в простой опечатке. В вашем файле .env измените это:

MAIL_DRIVER=smtp MAIL_HOST=mailtrap.io

к этому:

MAIL_DRIVER=smtp MAIL_HOST=smtp.mailtrap.io

Я добавил smtp. к хосту

person Chukky Nze    schedule 20.09.2018

После изменения настроек вам необходимо запустить: php artisan config: cache

Без них laravel будет использовать старые.

person Stefan C    schedule 05.04.2017

.env

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=yourmailIDpassword
MAIL_ENCRYPTION=tls

config / mail.php

?php

return [

/*
|--------------------------------------------------------------------------
| Mail Driver
|--------------------------------------------------------------------------
|
| Laravel supports both SMTP and PHP's "mail" function as drivers for the
| sending of e-mail. You may specify which one you're using throughout
| your application here. By default, Laravel is setup for SMTP mail.
|
| Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses",
|            "sparkpost", "log", "array"
|
*/

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

/*
|--------------------------------------------------------------------------
| SMTP Host Address
|--------------------------------------------------------------------------
|
| Here you may provide the host address of the SMTP server used by your
| applications. A default option is provided that is compatible with
| the Mailgun mail service which will provide reliable deliveries.
|
*/

'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

/*
|--------------------------------------------------------------------------
| SMTP Host Port
|--------------------------------------------------------------------------
|
| This is the SMTP port used by your application to deliver e-mails to
| users of the application. Like the host we have set this value to
| stay compatible with the Mailgun e-mail application by default.
|
*/

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

/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/

'from' => [
    'address' => env('MAIL_FROM_ADDRESS', '[email protected]'),
    'name' => env('MAIL_FROM_NAME', 'Example'),
],

/*
|--------------------------------------------------------------------------
| E-Mail Encryption Protocol
|--------------------------------------------------------------------------
|
| Here you may specify the encryption protocol that should be used when
| the application send e-mail messages. A sensible default using the
| transport layer security protocol should provide great security.
|
*/

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

/*
|--------------------------------------------------------------------------
| SMTP Server Username
|--------------------------------------------------------------------------
|
| If your SMTP server requires a username for authentication, you should
| set it here. This will get used to authenticate with your server on
| connection. You may also set the "password" value below this one.
|
*/

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

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

/*
|--------------------------------------------------------------------------
| Sendmail System Path
|--------------------------------------------------------------------------
|
| When using the "sendmail" driver to send e-mails, we will need to know
| the path to where Sendmail lives on this server. A default path has
| been provided here, which will work well on most of your systems.
|
*/

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

/*
|--------------------------------------------------------------------------
| Markdown Mail Settings
|--------------------------------------------------------------------------
|
| If you are using Markdown based email rendering, you may configure your
| theme and component paths here, allowing you to customize the design
| of the emails. Or, you may simply stick with the Laravel defaults!
|
*/

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

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

/*
|--------------------------------------------------------------------------
| Log Channel
|--------------------------------------------------------------------------
|
| If you are using the "log" driver, you may specify the logging channel
| if you prefer to keep mail messages separate from other log entries
| for simpler reading. Otherwise, the default channel will be used.
|
*/

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

];

приложение / HTTP / Контроллеры / yourcontroller.php

use App\Mail\sendMail;
use Mail;

public function fnmail($name,$password,$userid,$email)
{ 
  $data = array('name'=>$name, 'password' => $password, 'userid' => $userid);
  Mail::send('mail', $data, function($message) use ($name, $email) {
  $message->to($email, $name)
        ->subject('Subject');  //to redirect mail.blade.php page
  $message->from('[email protected]','DoNotReply');
  });
}

затем создайте папку в приложении .. имя папки - Mail, в этой папке создайте файл sendMail.php

sendMail.php

<?php

namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class sendMail extends Mailable
{
use Queueable, SerializesModels;

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

/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    return $this->view('register'); //to redirect register page
}
}

затем добавьте resources / views / mail.blade.php

mail.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Mail Sending</title>
</head>
<body>
  <table align='center' style='height: 200px;width: 200px'>
   <tr><td colspan='2' bgcolor='skyblue' style='text-align: center;font-weight: 
  bold;size: 20px;'><label> Mail Check </label></td></tr>
   <tr bgcolor='#fff7e6'>
   <tr><td style='color: magenta;font-weight: bold;'><label><b>Your UserName:</b> 
 </label></td><td><b>{{$name}}</b></td></tr><br>
   <tr><td style='color: magenta;font-weight: bold;'><label><b>Your LoginID:</b> 
 </label></td><td><b>{{$userid}}</b></td></tr><br>
 <tr><td style='color: magenta;font-weight: bold;'><label><b>Your Password:</b> 
 </label></td><td><b>{{$password}}</b></td><br></tr>
</tr>
<tr><td colspan='2' align='center' bgcolor='orange'><a 
href='http://localhost/larashop/laravelProject/public/login'>
<button>Login</button></a></td></tr></table>
</body>
</html>
person Ramya    schedule 22.07.2019

Отредактируйте и следуйте этому файлу: config / mail.php

'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => env('MAIL_HOST', 'your mail host'),
'port' => env('MAIL_PORT', '465'),
'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'Your email address'),
        'name' => env('MAIL_FROM_NAME', 'Your email Name'),
'encryption' => env('MAIL_ENCRYPTION', 'ssl'),

Не трогайте эти две строки

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

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

Отредактируйте и следуйте этому файлу: /.env

MAIL_DRIVER=smtp
MAIL_HOST=your mail host
MAIL_PORT=465
MAIL_USERNAME=Your smtp email address
MAIL_PASSWORD=Your smtp password
MAIL_ENCRYPTION=ssl

MAIL_FROM_ADDRESS=Your email address
MAIL_FROM_NAME="Your email Name"

Используйте нижеприведенную команду мастера.

Очистить кеш с помощью команды artisan

Конфигурация php artisan: очистить

Очистить конфигурацию

php artisan cache: очистить

Перезагрузите ваш сервер

sudo service httpd перезапуск

Будет работа! Наслаждайтесь кодированием

person Tola LENG    schedule 13.02.2019

Отредактируйте .env файл:

MAIL_HOST=smtp.gmail.com

Отредактируйте Config/mail.php файл:

'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

.env и mail.php должны соответствовать друг другу.

person Derrick    schedule 19.09.2019

Следуй этим шагам

  1. php artisan route:clear

  2. php artisan config:clear

  3. php artisan config:clear

после выполнения вышеуказанных 3 шагов снова запустите сервер и проверьте

person Nazmul Hoque    schedule 05.07.2021