Ошибка подключения к серверу smtp 110

This is my code and still it is not sending the mail. What could be the problem?

require 'class.phpmailer.php';// path to the PHPMailer class
require 'class.smtp.php';

            $mail = new PHPMailer();  

            $mail->IsSMTP();  // telling the class to use SMTP
            $mail->Mailer = "smtp";
            $mail->Host="smtp.gmail.com";
            $mail->SMTPSecure='tls';
            $mail->Port =465;             
            $mail->SMTPAuth = true; // turn on SMTP authentication
            $mail->Username = "mymailgmail.com"; // SMTP username
            $mail->Password = "mypassword"; // SMTP password 
            $mail->SMTPDebug = 1;

            $mail->AddAddress("mymail@gmail.com","Title");
            $mail->SetFrom($visitor_email, $name);
            $mail->AddReplyTo($visitor_email,$name);

            $mail->Subject  = "Message from  Contact form";
            $mail->Body     = $user_message;
            $mail->WordWrap = 50;  

            if(!$mail->Send()) {
            echo 'Message was not sent.';
            echo 'Mailer error: ' . $mail->ErrorInfo;
            } else {
            echo 'Message has been sent.';
            }

// header(‘Location: thank-you.html’);
}

  • phpmailer
  • php

asked Sep 3, 2013 at 9:36

andy's user avatar

andyandy

1,9475 gold badges27 silver badges46 bronze badges

4

  • Still nothing. Could it b a problem with where am hosting my files?

    Sep 3, 2013 at 10:38

  • I’d start looking in the direction to find out why the error message says it was trying to connect to port 110 whereas you attempted to configure PHPMailer to use port 465.

    Sep 3, 2013 at 11:58

  • this answer helped me. I used 587 port and 465 didn’t work for me.

    Apr 2, 2014 at 18:51

1 Answer

I had similar issue sometime back. It turned out that the connection was attempted using ipv6 address. It worked fine after removing IPv6 address from network interface.

answered Oct 1, 2013 at 12:36

Selvamuthukumar's user avatar

2

  • Thank you, you saved my life!!! :D, but do you know the reason why ipv6 brings problems?

    Jan 7, 2016 at 20:45

  • @sergio-guillen-mantilla In my case the router/gateway in the network did not support IPv6. Packets were dropped in the gateway.

    Mar 16, 2016 at 12:09

Будучи менеджером коммерческого отдела небольшой торговой компании, я выполнял задачу по отправке нескольких сотен писем постоянным и потенциальным клиентам. Базу формировали из открытых источников мы сами, предложение было реально интересным целевой аудитории. Возникла «неожиданная» проблема – часть писем стала возвращаться. Кроме того, начали приходить сообщения с указаниями кодов ошибки SMTP. Своего IT-специалиста в штате у нас не было, потому разобраться с проблемой я решил самостоятельно. О результатах этой работы, причинах возникновения таких ошибок и методах их решения расскажу в этой статье.

Ошибка SMTP

Как избежать ошибок при составлении и отправке писем

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

Самый простой способ это понять – отправить тестовое сообщение на свой ящик. Затем следует протестировать его отправку и получение, используя разные внешние почтовые сервисы: gmail, yandex, mail, rambler и другие. Если сообщение получено, следует ответить на него, проверив корректность исполнения команды «RE» вашим почтовым сервером и принятие ответа условным отправителем.

Довольно часто проблемы с попаданием писем в папку «Спам» или программной блокировкой на стороне получателя лежат в неверном оформлении ключевых полей. Особенно это касается массовых рассылок коммерческого характера. Для отправки большого количества однотипных сообщений как минимум потребуется выполнение следующих параметров настройки:

  • выделенный IP-адрес с целью исключить блокировку на стороне сервера-ретранслятора или почтовой программы конечного получателя;
  • криптографические подписи DKIM и SPF, помогающие подтвердить подлинность домена и минимизировать количество писем, воспринимаемых как спам.

Важно! В случае несоблюдения этих элементарных правил вы рискуете не только тем, что конкретное письмо не будет доставлено адресату. При многократных попытках отправки письма в большинстве почтовых программ в блок-лист попадет вся корреспонденция, отправляемая с вашего email, и даже корпоративный домен (@domain.***).

Некорректное использование бота для отправки писем может привести к блокировке отправителя и другим нежелательным последствиям. Даже если информация, которую вы отправляете потенциальным клиентам, реально интересна им, система спам-фильтрации может воспринять данную рассылку как вредоносную. Чтобы избежать этого, лучше всего воспользоваться услугами специализированных компаний.

В моей практике был случай, когда никак не удавалось добиться получения моей электронной корреспонденции одним из сотрудников компании «Лукойл». Письма я отправлял самые простые, используя корпоративный ящик. Только после того, как мой респондент обратился в IT-службу своего предприятия, выяснилось, что данный адрес находится в блэк-листе. Попал он туда из-за каких-то ошибок, допущенных моим предшественником. Понадобилось больше недели, чтобы адрес включили в «белый список». Все это время письма, высылаемые с личного mail@yandex.ru, доходили без проблем.

Полезно: Почему не приходят письма с сайта. Пример частного случая.

Комьюнити теперь в Телеграм

Подпишитесь и будьте в курсе последних IT-новостей

Подписаться

SMTP (Simple Mail Transfer Protocol) — это протокол, используемый большинством почтовых программ для отправки электронных сообщений в сети интернет. Некорректное взаимодействие между серверами, индивидуальные настройки на уровне программного обеспечения и многие другие причины приводят к появлению ошибок. В этом случае письма не доходят до получателей, возвращаются обратно или просто «пропадают». При возникновении таких ситуаций отправитель получает сообщение о наличии конкретной ошибки, отражающей SMTP-код последнего отклика сервера.

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

Первая цифра комбинации содержит информацию о качестве доставки:

  • сообщение доставлено («SMTP OK»);
  • возникла неизвестная или временная проблема («SMTP unknown»);
  • критическая ошибка («SMTP error»). 

Существует четыре варианта значений для первой цифры кода:

  • 2xx – положительный результат, есть возможность передачи следующей команды;
  • 3xx – отложенный результат, необходимо осуществление дополнительных действий;
  • 4xx – сообщение не принято, но проблема носит временный характер, и запрос может быть повторен через какое-то время; 
  • 5xx – категорический отказ выполнения команды, отправка запроса со стороны передающего сервера в том же виде невозможна. 

Вторая цифра в коде сообщает о категории ответа:

  • 0 – синтаксические ошибки; 
  • 1 – ответы на запросы информации; 
  • 2 – ошибки канала передачи; 
  • 3 и 4 – неизвестный тип ошибки;
  •  5 – статус почтовой системы.

Третья цифра дает более расширенную информацию о значении, указанном во второй цифре SMTP-ответа.

Помимо цифровой комбинации, SMTP-сообщение может содержать дополнительную текстовую информацию.

Полную информацию о кодах, их компоновке и значениях можно найти в спецификациях RFC 5321 и RFC 1893.

Следует учитывать, что SMTP-message говорит об успешном или неудачном варианте доставки именно на уровне взаимодействия почтовых серверов. Положительный ответ вовсе не означает, что ваше письмо не попало в папку «Спам».

Читайте также

Как настроить почту в Outlook

Почему письма не отправляются с электронной почты

Виды почтовых сервисов

На программном уровне существует несколько видов обработки электронной почтовой корреспонденции. К первой группе относятся виртуальные сервисы, доступные чаще всего в бесплатном исполнении через интернет-соединение на сайте почтового сервера. Это всем известные ресурсы: 

  • Gmail/Google Suite (почта от Google.com);
  • Yandex.ru;
  • Mail.ru; 
  • Rambler.ru и другие.

Более подробную информацию о значениях ответов SMTP можно получить на сайтах популярных почтовых сервисов:

  • Коды ошибок SMTP почтового сервиса Gmail (Google Suite) (support.google.com)
  • Создание и отправка писем на сервисе Яндекс
  • Ошибки отправки писем при использовании сервера и сервиса Mail.ru

Ко второй группе относятся почтовые клиенты – программы, обладающие более расширенным функционалом, чем виртуальные сервисы. Наиболее популярными и универсальными почтовыми клиентами для Windows являются:

  • Opera Mail;
  • Mozilla Thunderbird;
  • Koma-Mail;
  • SeaMonkey;
  • The Bat!;
  • Microsoft Outlook.

Принципы работы почтовых клиентов несколько отличаются от процесса обработки корреспонденции виртуальными серверами. При отправке сообщения программа отсылает его не напрямую конечному получателю, а ретранслирует через сервер-релей. Этот процесс осуществляется чаще всего с использованием протокола SMTP, а получение корреспонденции обычно происходит с помощью IMAP или POP.

Коды SMTP-ответов определяются стандартом. Администратор почтового сервера может создать собственные настройки, в том числе и в части кодировки ответов сервера. Особенно это касается локальных почтовых программ, установленных непосредственно на сервере какой-нибудь компании.

О вариантах выбора и способах создания корпоративных почтовых сервисов более подробно можно прочитать здесь: Что такое почтовый сервер и зачем он нужен.

Чипсендер

Классификация отрицательных SMTP-сообщенийЯ настроил свою почтовую программу – локальный клиент (MS Outlook и т.п.) или бесплатную почту на gmail или yandex. Начинаю отправлять письма, но сталкиваюсь с различными проблемами, связанными с тем, что мои респонденты не получают направленную им корреспонденцию. Соответственно, на мой ящик приходят сообщения об ошибках в виде кодировок SMTP. 

Сразу опускаю тот пакет сообщений, которые начинаются с 2хх и 3хх, так как они содержат информацию о том, что задача получения письма уже решена положительно либо получит такой статус в ближайшее время. Более подробно рассмотрим некоторые виды кодированных сообщений, начинающихся с 4хх и 5хх, т.е. отклики SMTP-сервера, которые сообщают о наличии проблем.

Почтовый сервер сообщил об ошибке 421

Значение: Service Not Available. Сервер недоступен: канал связи будет закрыт.

Возможные причины

Варианты решения

Неправильно заданы параметры SMTP-соединения

Необходимо перепроверить настройки

Брандмауэр блокирует IP-адрес сервера электронной почты

Необходимо создать новое правило в брандмауэре

Блокируется трафик через порт 25

Попробуйте в настройках учетной записи электронной почты сменить номер порта SMTP на 465

Проблема использования VPN

Необходимо, чтобы провайдер услуги занес ваш почтовый сервер в белый список адресов VPN

Данная ошибка возникает наряду с грейлистингом (Greylisting «Серый список») при интенсивном использовании бесплатного SMTP-сервера, который лимитирует количество отправляемых сообщений в единицу времени. Для решения этой проблемы можно воспользоваться высоконагруженным SMTP-сервером. Чаще всего эта услуга является платной.

Получено сообщение с кодом 451

Значение: Requested action aborted: local error in processing. Требуемое действие прерывалось: ошибка в обработке.

Возможные причины

Варианты решения

Превышено количество допустимых подключений или лимит обмена сообщениями за отрезок времени, письма ждут отправки в очереди

В настройках сервера увеличить лимит или задать ограничение не на количество подключений, а на количество писем на одного пользователя. Накопившуюся очередь писем можно отправить повторно командой «force send»

Неправильно настроены MX-записи домена, из-за чего происходит неправильная маршрутизация писем

Проверьте логи, конфигурационные файлы, МХ-записи и разрешения, внесите корректировки

Устранение проблем с доставкой электронной почты для кода ошибок 451 4.7.500–699 (ASxxx) в Exchange Online. Электронная почта из доменов onmicrosoft.com ограничена и фильтруется для предотвращения спама.

Необходимо добавить настраиваемый домен.

Ошибка почтового сервера 452

Значение: Insufficient system resources. Запрашиваемое действие не выполнено: недостаточно места в системе.

Возможные причины

Варианты решения

На сервере получателя закончилось место, поэтому письмо не доставляется

Чтобы в этом убедиться, достаточно попробовать осуществить отправку письма с другого сервера

В сообщении присутствует текст «Out of memory». Это значит, что недостаточно места на вашем сервере

Необходимо проверить количество отправляемых писем в очереди, наличие свободного места на диске и объем доступной памяти

В Microsoft Exchange Server есть специальный компонент мониторинга доступных ресурсов Back Pressure, который отслеживает свободное место на диске, на котором хранятся очереди транспортной службы Exchange. При возникновении такой ошибки можно сделать следующее:

  • очистить диск от ненужных файлов;
  • отключить мониторинг Back Pressure (не рекомендуется);
  • перенести транспортную очередь на другой диск достаточного объема.

Доставка письма

Сервер сообщил об ошибке SMTP 550

Значение:  Mailbox unavailable. Требуемые действия не предприняты: электронный ящик недоступен

Возможные причины

Варианты решения

Неверно указан email-адрес получателя

Необходимо связаться с адресатом альтернативным способом и уточнить правильность написания адреса, а также убедиться, что он является действующим

Система заражена вирусом, осуществляющим массовую рассылку писем с вашего адреса

Провести полную проверку специализированной антивирусной программой

На стороне вашего интернет-провайдера установлены ограничения на отправку исходящих сообщений

Необходимо связаться с поставщиком интернет-услуг и получить консультацию по устранению данной проблемы

Сервер получателя не работает

Отправьте тестовое письмо на другой почтовый сервер. Свяжитесь с получателем и сообщите о проблеме

Данная ошибка может возникнуть из-за настроек программы Антиспам на стороне получателя. Проверьте корректность оформления вашего письма и другие параметры, по которым ваше сообщение может быть отнесено к нежелательным.

Почтовый сервер ответил ошибкой 571

Значение:  SMTP Protocol Returned a Permanent Error 571 xxx@mail.ru prohibited. We do not relay/Spam message rejected. Ошибка на стороне получателя почты.

Возможные причины

Варианты решения

Ваш IP-адрес заблокирован на стороне конечного получателя спам-фильтром, антивирусом или файрволом

Данную проблему может решить только администратор сети получателя, исключив ваши идентификационный данные из списка блокировки или добавив их в «белый список»

Неверные учетные данные ретранслятора. У вас нет разрешения на отправку электронной почты через сервер, который находится между вами и получателем

Обратитесь к администратору данного ресурса для изменения настроек

У IP отправителя нет RDNS

Проверьте настройки получения писем и разрешения для доменов-отправителей

Как я уже писал выше, разные почтовые серверы накладывают свои ограничения на прием и отправку сообщений. Код 571 в Google Suite расшифровывается следующим образом: «Действующая политика запрещает отправку этого сообщения». Письмо может содержать защищенные или конфиденциальные данные – номера кредитных карт и т.п. Или политика администрирования запрещает отправку определенными пользователями сообщений адресатам вне установленной группы.

Сертификат почтового сервера недействителен

Предупреждение безопасности интернетаОбычно с таким сообщением приходится сталкиваться пользователям, у которых настроен Microsoft Exchange Server/MS Outlook. В данной ситуации самое простое решение – обновить сертификат.

Проверка доступности почтового сервера программным методом

В данной статье описаны лишь некоторые варианты ошибок, которые могут возникнуть при отправке электронных сообщений. Полный перечень достаточно объемен и во многом зависит от настроек конкретного сервера как на стороне отправителя, так и получателя. Некоторые из ошибок могут быть легко устранены обычным пользователем, другие под силу лишь опытным администраторам.

Одним из способов предупреждения появления ошибок является онлайн-проверка доступности почтового сервера с помощью бесплатных инструментов:

  • https://mxtoolbox.com
  • https://www.ultratools.com
  • http://mail2web.com

Эти сервисы пробуют подключиться к почтовому серверу по SMTP, подтверждают, что у него есть запись обратной зоны DNS, и замеряют время отклика. С их помощью можно диагностировать некоторые ошибки службы почтовых серверов или проверить, не занесен ли данный ресурс в черные списки из-за спама.

Прочитав эту статью, обратите внимание на то, как настроен ваш почтовый сервер на получение сторонних писем по SMTP-протоколу. Быть может, в данный момент ваш антиспам или локальная политика фильтрации входящих сообщений блокирует получение очень важного и нужного для вас месседжа? Проверьте сами или обратитесь к системному администратору. Если ошибку с SMTP никак не удается решить, то попробуйте обратиться в службу поддержки почтового сервера.

Содержание

  1. Причина: приложение Outlook не подключено к Интернету или к сети.
  2. Причина: некоторые учетные записи электронной почты POP и IMAP используют сервер исходящей почты (SMTP), для которого требуется проверка подлинности.
  3. Причина: поставщик услуг Интернета или администратор сети использует брандмауэр, блокирующий подключения к серверу исходящей почты (SMTP) вашей службы электронной почты.
  4. Причина: учетные данные или параметры учетной записи неверны.
  5. Причина: сети требуется прокси-сервер для подключения к почтовому серверу.
  6. Причина: сервер электронной почты недоступен.

Если не получается отправить письмо из 1С и появляется такая ошибка:

Не удалось подключиться к серверу исходящей почты:Временная ошибка сервера. (SMTP error code 435 Unable to authenticate at present:)
Не удалось подключиться к серверу входящей почты:Произошла ошибка при работе с POP3. Код ошибки: 2

Это говорит о том, что вы неправильно узнали настройки smtp вашей почты.
Следует перенастрой отправку данных для smtp таким образом, как указано на на сайте поставщика почты Обычно в разделе помощ или настройка и прописать их в 1с в системной учётной записи. Выглядит примерно так :

Я получаю ошибку SMTP с PHP Mailer и SMTP Outlook. Я запутался здесь, потому что он работает нормально на localhost с номером порта 25, но он не работает на сервере хостинга, я пробовал все порты с SSL и TLS.

Ошибка: SMTP ERROR: Не удалось подключиться к серверу: время ожидания подключения (110)

Мой код:

Пожалуйста, помогите мне решить эту проблему. У меня есть общий хостинг Linux.

У меня была аналогичная проблема, и оказалось, что мой хост (Bluehost) заблокировал исходящие соединения на порту 465. Я отправлю решение здесь в надежде, что это поможет вам. Но я недостаточно эксперт, чтобы узнать, есть ли такая же проблема или нет.

Я нашел замечательный способ, который исправил это для меня:

  1. В редакторе DNS-зоны cPanel найдите раздел MX (Mail Exchanger) и выберите «удаленный почтовый обменник».
  2. В разделе учетных записей cPanel создайте соответствующий адрес электронной почты (не пропустите это)
  3. Не используйте «smtp.live.com» в качестве вашего хоста smtp. Используйте smtp-хост вашего общего хостинга Linux-хостинга. Я не знаю, как ты получишь. Шахта – boxXXXX.bluehost.com.
  4. Задайте свое имя пользователя и пароль таким же, как учетная запись электронной почты, которую вы только что установили в cPanel.

Ни один из ответов не работал для меня. После многих часов я нашел проблему, но работает только для Cpanel / WHM

  • Войдите в WHM.
  • Перейдите на вкладку ConfigServer Security & Firewall внутри плагинов.
  • Нажмите «Настройка брандмауэра»
  • Фильтровать по настройкам SMTP
  • Найдите параметр SMTP_ALLOWUSER и добавьте имя пользователя учетной записи Cpanel, разделенное комой
  • Перезапустите брандмауэр.

Если у вас нет доступа к WHM, обратитесь к своему провайдеру.

Мост, вероятно, phpmailer не поддерживается вашим хостингом. Вам необходимо пройти проверку, создав новый файл и проверить простую функцию электронной почты php. Скорее всего, SMTP не настроен у вашего хостинг-провайдера

Мой код правильный.
Проблема была в Хостинг-провайдере. Я связался с ними об этом, и они сделали некоторую конфигурацию на своем сервере, и все сделано.

Примечание: Мы стараемся как можно оперативнее обеспечивать вас актуальными справочными материалами на вашем языке. Эта страница переведена автоматически, поэтому ее текст может содержать неточности и грамматические ошибки. Для нас важно, чтобы эта статья была вам полезна. Просим вас уделить пару секунд и сообщить, помогла ли она вам, с помощью кнопок внизу страницы. Для удобства также приводим ссылку на оригинал (на английском языке) .

Причина: приложение Outlook не подключено к Интернету или к сети.

Решение: подключите компьютер к Интернету или к сети.

Откройте веб-браузер, чтобы увидеть, есть ли доступ к сайтам в Интернете. Если вы находитесь в локальной сети, проверьте, можно ли открыть сайты интрасети. Сведения о том, как проверить состояние сетевых подключений, см. в справке Mac OS.

Решение: убедитесь в том, что Outlook подключен к Интернету.

В меню Outlook посмотрите, не установлен ли флажок Автономная работа.

Причина: некоторые учетные записи электронной почты POP и IMAP используют сервер исходящей почты (SMTP), для которого требуется проверка подлинности.

Решение: включите проверку подлинности SMTP для учетной записи POP или IMAP.

Некоторые службы электронной почты, включая учетных записей электронной почты iCloud, требуют проверки подлинности для их SMTP-сервера. Если вы убедитесь, что все параметры учетной записи заданы правильно, но вы по-прежнему не удается отправлять сообщения, попробуйте отключить проверку подлинности SMTP.

В меню Сервис выберите учетные записи.

В левой области диалогового окна Учетные записи выберите учетную запись.

В разделе SMTP-сервер выберите Дополнительные параметры .

Во всплывающем меню Проверка подлинности выберите тип проверки подлинности и введите необходимые учетные данные.

Причина: поставщик услуг Интернета или администратор сети использует брандмауэр, блокирующий подключения к серверу исходящей почты (SMTP) вашей службы электронной почты.

Решение: узнайте, не могут ли ваш поставщик услуг Интернета или администратор сети предоставить альтернативный SMTP-сервер для вашей учетной записи POP или IMAP.

При наличии адреса альтернативного SMTP-сервера укажите его в параметрах учетной записи.

В меню Сервис выберите учетные записи.

В левой области диалогового окна Учетные записи выберите учетную запись.

В поле сервер исходящей почты введите имя или адрес сервера.

Примечание: При использовании ноутбука в нескольких расположениях, таких как дома и на работе, SMTP-сервер, который используется в одном месте может не работать в других местах. Каждый к Интернету, с помощью которой вы, возможно, брандмауэр с ограничениями собственный.

Причина: учетные данные или параметры учетной записи неверны.

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

В меню Сервис выберите учетные записи.

В левой области диалогового окна Учетные записи выберите учетную запись.

Убедитесь в том, что вы ввели правильный адрес электронной почты, имя пользователя и пароль.

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

Причина: сети требуется прокси-сервер для подключения к почтовому серверу.

Решение: укажите почтовый прокси-сервер в разделе «Системные настройки» на компьютере.

Если вы используете сети для подключения к Интернету, может потребоваться указать почты прокси-сервер. Обратитесь к администратору сети для правильные параметры для вашего почтового прокси-сервер. Инструкции о том, как вводить эти параметры, обратитесь к справочной системе Mac OS.

Причина: сервер электронной почты недоступен.

Решение: проверьте, работает ли почтовый сервер.

Если вы раньше успешно подключались к этой учетной записи, возможно, проблема в том, что почтовый сервер отключен. Обратитесь к поставщику услуг электронной почты или администратору сети, чтобы узнать, работает ли почтовый сервер.

Я получаю ошибку SMTP с PHP Mailer и SMTP Outlook. Я запутался здесь, потому что он работает нормально на localhost с номером порта 25, но он не работает на сервере хостинга, я пробовал все порты с SSL и TLS.

Пожалуйста, помогите мне решить эту проблему. У меня есть общий хостинг Linux.

У меня была аналогичная проблема, и оказалось, что мой хост (Bluehost) заблокировал исходящие соединения на порту 465. Я отправлю решение здесь в надежде, что это поможет вам. Но я недостаточно эксперт, чтобы узнать, есть ли такая же проблема или нет.

Я нашел замечательный способ, который исправил это для меня:

  1. В редакторе DNS-зоны cPanel найдите раздел MX (Mail Exchanger) и выберите «удаленный почтовый обменник».
  2. В разделе учетных записей cPanel создайте соответствующий адрес электронной почты (не пропустите это)
  3. Не используйте «smtp.live.com» в качестве вашего хоста smtp. Используйте smtp-хост вашего общего хостинга Linux-хостинга. Я не знаю, как ты получишь. Шахта – boxXXXX.bluehost.com.
  4. Задайте свое имя пользователя и пароль таким же, как учетная запись электронной почты, которую вы только что установили в cPanel.

Ни один из ответов не работал для меня. После многих часов я нашел проблему, но работает только для Cpanel / WHM

  • Войдите в WHM.
  • Перейдите на вкладку ConfigServer Security & Firewall внутри плагинов.
  • Нажмите «Настройка брандмауэра»
  • Фильтровать по настройкам SMTP
  • Найдите параметр SMTP_ALLOWUSER и добавьте имя пользователя учетной записи Cpanel, разделенное комой
  • Перезапустите брандмауэр.

Если у вас нет доступа к WHM, обратитесь к своему провайдеру.

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

Мост, вероятно, phpmailer не поддерживается вашим хостингом. Вам необходимо пройти проверку, создав новый файл и проверить простую функцию электронной почты php. Скорее всего, SMTP не настроен у вашего хостинг-провайдера

 <?php $to = "somebody@example.com"; $subject = "My subject"; $headers = "From: webmaster@example.com" . "\r\n" . "CC: somebodyelse@example.com"; mail($to,$subject,$headers); ?> при <?php $to = "somebody@example.com"; $subject = "My subject"; $headers = "From: webmaster@example.com" . "\r\n" . "CC: somebodyelse@example.com"; mail($to,$subject,$headers); ?> 

Мой код правильный.
Проблема была в Хостинг-провайдере. Я связался с ними об этом, и они сделали некоторую конфигурацию на своем сервере, и все сделано.

 

Добрый день. Установил пробную версию Битрикс24 («1С-Битрикс24» — Корпоративный портал 18.1.5) отсюда

https://www.1c-bitrix.ru/download/intranet.php

. В процессе установки возникли две ошибки подключения к БД, но при повторении шага снова не появлялись, то есть проект был установлен без ошибок. При попытке подключить почту, выдает сообщение «Ошибка подключения к серверу». Раньше всё было в порядке, был точно так же установленный проект, в котором приходилось активно работать с отладчиком (xdebug на phpstorm), нужно было доработать оповещение об отправлении письма, не предусмотренное стандартным функционалом. В процессе доработки и появилась эта ошибка. После этого дважды переустанавливал проект, что не помогло решить проблему. Пробовал подключиться и через imap и не через imap — результат один и тот же.

 

Пользователь 1488151

Эксперт

Сообщений: 290
Баллов: 74
Регистрация: 18.10.2017

#2

0

08.04.2019 04:29:51

Цитата
ivanweber написал:
Добрый день. Установил пробную версию Битрикс24 («1С-Битрикс24» — Корпоративный портал 18.1.5) отсюда  https://www.1c-bitrix.ru/download/intranet.php . В процессе установки возникли две ошибки подключения к БД, но при повторении шага снова не появлялись, то есть проект был установлен без ошибок. При попытке подключить почту, выдает сообщение «Ошибка подключения к серверу». Раньше всё было в порядке, был точно так же установленный проект, в котором приходилось активно работать с отладчиком (xdebug на phpstorm), нужно было доработать оповещение об отправлении письма, не предусмотренное стандартным функционалом. В процессе доработки и появилась эта ошибка. После этого дважды переустанавливал проект, что не помогло решить проблему. Пробовал подключиться и через imap и не через imap — результат один и тот же.

Логин состоит без @yandex.ru

 

arnly, к сожалению, не помогло

 

Пользователь 1488151

Эксперт

Сообщений: 290
Баллов: 74
Регистрация: 18.10.2017

#4

0

08.04.2019 16:03:51

Цитата
ivanweber написал:
arnly , к сожалению, не помогло

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

 

Пользователь 1488151

Эксперт

Сообщений: 290
Баллов: 74
Регистрация: 18.10.2017

#5

0

08.04.2019 16:06:21

Цитата
arnly написал:

Цитата
ivanweber  написал:
arnly , к сожалению, не помогло

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

Что-то типо этого:

https://yandex.ru/support/mail/web/preferences/filters/forwarding.html#fw-doesnt-work

Не указаны персональные данные в Яндекс.Паспорте

Укажите в Яндекс.Паспорте достоверные персональные данные и привяжите к аккаунту номер телефона. Возможно, наша система безопасности сочла ваш аккаунт подозрительным и заблокировала ящик. Чаще всего это происходит из-за того, что к ящику не привязан номер телефона или в Паспорте указаны вымышленные имя и фамилия. На снятие блокировки обычно уходит пара часов.

 

А про пару часов скажу сразу, это бред. Минимум через сутки только работать начнёт, если повезёт. У mail.ru точно такая же защита.

 

arnly, пробовал и к новой почте подвязывать с тем же исходом, возможно ли, что по ip блокируют?

 

Попробовал ещё через почту рамблера по imap подключиться с тем же исходом. Повторюсь, проблема возникла при работе над сайтом с использованием отладчика xdebug в phpstorm. После этого я скачал новый дистрибутив и в рамках установки Б24 создавалась новая база. Сайт ставил на Open Server, в том числе ещё тогда, когда проблемы с подключением не возникало. Может ли быть так, что из-за работы с отладчиком я поломал какие-нибудь сетевые настройки компьютера? И если да, то какие например?

 

Пользователь 292840

Заглянувший

Сообщений: 1
Регистрация: 24.06.2015

#9

0

25.01.2020 02:01:56

Та же самая проблема. Ошибка подключения к серверу (110). Пароль перепроверил. Попробовал разные почты. Всегда — эта ошибка.
ХЭЛП.
Куплена коробочная версия Сайт+Битрикс 24.

Am trying to send mail to a gmail address but it keeps on getting this error «SMTP -> ERROR: Failed to connect to server: Connection timed out (110)SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed.» What could be the problem?

        require 'class.phpmailer.php'; // path to the PHPMailer class
        require 'class.smtp.php';

            $mail = new PHPMailer();


            $mail->IsSMTP();  // telling the class to use SMTP
            $mail->SMTPDebug = 2;
            $mail->Mailer = "smtp";
            $mail->Host = "ssl://smtp.gmail.com";
            $mail->Port = 587;
            $mail->SMTPAuth = true; // turn on SMTP authentication
            $mail->Username = "myemail@gmail.com"; // SMTP username
            $mail->Password = "mypasswword"; // SMTP password 
            $Mail->Priority = 1;

            $mail->AddAddress("myemail@gmail.com","Name");
            $mail->SetFrom($visitor_email, $name);
            $mail->AddReplyTo($visitor_email,$name);

            $mail->Subject  = "Message from  Contact form";
            $mail->Body     = $user_message;
            $mail->WordWrap = 50;  

            if(!$mail->Send()) {
            echo 'Message was not sent.';
            echo 'Mailer error: ' . $mail->ErrorInfo;
            } else {
            echo 'Message has been sent.';
            }

AnFi's user avatar

AnFi

10.4k3 gold badges23 silver badges47 bronze badges

asked Aug 28, 2013 at 19:29

Muli's user avatar

4

Remove or comment out the line-

$mail->IsSMTP();

And it will work for you.

I have checked and experimented many answers from different sites but haven’t got any solution except the above solution.

dario's user avatar

dario

5,12912 gold badges28 silver badges32 bronze badges

answered Aug 10, 2015 at 12:51

Snehasis's user avatar

SnehasisSnehasis

9156 silver badges10 bronze badges

17

You must to have installed php_openssl.dll, if you use wampserver it’s pretty easy, search and apply the extension for PHP.

In the example change this:

    //Set the hostname of the mail server
    $mail->Host = 'smtp.gmail.com';

    //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission 465 ssl
    $mail->Port = 465;

    //Set the encryption system to use - ssl (deprecated) or tls
    $mail->SMTPSecure = 'ssl';

and then you recived an email from gmail talking about to enable the option to Less Safe Access Applications
here https://www.google.com/settings/security/lesssecureapps

I recommend you change the password and encrypt it constantly

answered Oct 8, 2014 at 2:03

El David's user avatar

El DavidEl David

6068 silver badges17 bronze badges

2

You’ve got no SMTPSecure setting to define the type of authentication being used, and you’re running the Host setting with the unnecessary ‘ssl://’ (PS — ssl is over port 465, if you need to run it over ssl instead, see the accepted answer here. Here’s the lines to add/change:

+ $mail->SMTPSecure = 'tls';

- $mail->Host = "ssl://smtp.gmail.com";
+ $mail->Host = "smtp.gmail.com";

Community's user avatar

answered Aug 29, 2013 at 20:58

Dmitri DB's user avatar

Dmitri DBDmitri DB

3173 silver badges15 bronze badges

4

Are you running on Localhost? and have you edit the php.ini ?

If not yet, try this:
1. Open xampp->php->php.ini
2. Search for extension=php_openssl.dll
3. The initial will look like this ;extension=php_openssl.dll
4. Remove the ‘;’ and it will look like this extension=php_openssl.dll
5. If you can’t find the extension=php_openssl.dll, add this line extension=php_openssl.dll.
6. Then restart your Xampp.

Goodluck ;)

answered Jan 11, 2014 at 4:03

Sendoh Akira's user avatar

1

I know its been a while since this question but I had the exact problem and solved it by disabling SMTP_BLOCK on csf.conf (we use CSF for a firewall).

To disable just edit csf.conf and disable SMTP_BLOCK like so:

###############################################################################
# SECTION:SMTP Settings
###############################################################################
# Block outgoing SMTP except for root, exim and mailman (forces scripts/users
# to use the exim/sendmail binary instead of sockets access). This replaces the
# protection as WHM > Tweak Settings > SMTP Tweaks
#
# This option uses the iptables ipt_owner/xt_owner module and must be loaded
# for it to work. It may not be available on some VPS platforms
#
# Note: Run /etc/csf/csftest.pl to check whether this option will function on
# this server
# SMTP_BLOCK = "1" --> this will cause phpmailer Connection timed out (110)
SMTP_BLOCK = "0"

answered Jan 23, 2016 at 20:32

Goldbug's user avatar

GoldbugGoldbug

6076 silver badges8 bronze badges

1

i’ve had this problem in tell i recive an email from google telling me that someone try to login to your account is it you and i answer yes then it start workin so if this is the case for you look in your email and allow the server

answered Jul 16, 2016 at 12:59

user5778000's user avatar

2

Login your Google account at myaccount.google.com/security go to «Login» and then «Security», scroll to bottom then enable the «Allow less secure apps» option.

Daniel's user avatar

Daniel

1,23914 silver badges24 bronze badges

answered Dec 27, 2016 at 22:07

Hieu - 7347514's user avatar

Here is a list of this you should look into when dealing with PHPMailer:

  1. Enable openSSL by un-commenting extension=php_openssl.dll in your PHP.ini
  2. Use $mail->SMTPSecure = 'tls'; and $mail->Port = 587;
  3. Enable debugging for if you are going wrong somewhere else like incorrect username and password etc.

answered May 14, 2015 at 7:02

KKK's user avatar

KKKKKK

3,1295 gold badges34 silver badges58 bronze badges

You are doing all well. Just you have to check different SMTP ports like 465 and others that works on your system.
Another thing to keep in mind to allow access to the less secure apps by google account otherwise it throws the same error.
I have gone through it for a whole day and the only thing I am doing wrong is the port no., I just changed the port no. and it works.

answered Mar 7, 2017 at 13:59

Deepak Kumar's user avatar

Deepak KumarDeepak Kumar

6771 gold badge8 silver badges22 bronze badges

Mailjet

SMTP SETTINGS

Port: 25 or 587 (some providers block port 25)

I work by changing the port after deploying the app to the server.

  • In Debug it worked for me: $mail->Port = 25;
  • In Release it worked for me: $mail->Port = 587;

GL

answered Dec 19, 2018 at 2:13

Braian Coronel's user avatar

Braian CoronelBraian Coronel

21.7k4 gold badges54 silver badges59 bronze badges

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).

answered Aug 1, 2017 at 9:19

Akif Hussain Sayyed's user avatar

If it works on your localhost but not on your web host:

Some hosting sites block certain outbound SMTP ports. Commenting out the line $mail->IsSMTP(); as noted in the accepted answer may make it work, but it is simply disabling your SMTP configuration, and using the hosting site’s email config.

If you are using GoDaddy, there is no way to send mail using a different SMTP. I was using SiteGround, and found that they were allowing SMTP access from ports 25 and 465 only, with an SSL encryption type, so I would look up documentation for your host and go from there.

answered Apr 6, 2018 at 22:06

Stephanie's user avatar

StephanieStephanie

1332 silver badges7 bronze badges

        <?php
    require 'PHPMailer/PHPMailerAutoload.php';
    
    $mail = new PHPMailer();
    
    $mail->SMTPDebug = 0;                               // Enable verbose debug output
    
    
    $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->IsSMTP();
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'mail@gmail.com';                 // SMTP username
    $mail->Password = 'your pass';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to
    $mail->setFrom('mail@gmail.com');
    $mail->addAddress('mail@gmail.com');               // Name is optional
    
    
    $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.';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        echo 'Message has been sent';
    }
    
  ?>

THIS WORK FOR ME JUST WHEN YOU WANT TO TEST
DON’T USE IDE FOR TESTING THAT BECAUSE PROBABLY NOT WORK IF YOU IN LOCALHOST USE localhost/yourfile.php

answered Mar 17, 2021 at 16:56

MAX's user avatar

the solution is configure the gmail preferences, access to no secure application

CSchulz's user avatar

CSchulz

10.8k10 gold badges59 silver badges112 bronze badges

answered Jun 6, 2016 at 3:12

marcelo's user avatar

0

Am trying to send mail to a gmail address but it keeps on getting this error «SMTP -> ERROR: Failed to connect to server: Connection timed out (110)SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed.» What could be the problem?

        require 'class.phpmailer.php'; // path to the PHPMailer class
        require 'class.smtp.php';

            $mail = new PHPMailer();


            $mail->IsSMTP();  // telling the class to use SMTP
            $mail->SMTPDebug = 2;
            $mail->Mailer = "smtp";
            $mail->Host = "ssl://smtp.gmail.com";
            $mail->Port = 587;
            $mail->SMTPAuth = true; // turn on SMTP authentication
            $mail->Username = "myemail@gmail.com"; // SMTP username
            $mail->Password = "mypasswword"; // SMTP password 
            $Mail->Priority = 1;

            $mail->AddAddress("myemail@gmail.com","Name");
            $mail->SetFrom($visitor_email, $name);
            $mail->AddReplyTo($visitor_email,$name);

            $mail->Subject  = "Message from  Contact form";
            $mail->Body     = $user_message;
            $mail->WordWrap = 50;  

            if(!$mail->Send()) {
            echo 'Message was not sent.';
            echo 'Mailer error: ' . $mail->ErrorInfo;
            } else {
            echo 'Message has been sent.';
            }

AnFi's user avatar

AnFi

10.4k3 gold badges23 silver badges47 bronze badges

asked Aug 28, 2013 at 19:29

Muli's user avatar

4

Remove or comment out the line-

$mail->IsSMTP();

And it will work for you.

I have checked and experimented many answers from different sites but haven’t got any solution except the above solution.

dario's user avatar

dario

5,12912 gold badges28 silver badges32 bronze badges

answered Aug 10, 2015 at 12:51

Snehasis's user avatar

SnehasisSnehasis

9156 silver badges10 bronze badges

17

You must to have installed php_openssl.dll, if you use wampserver it’s pretty easy, search and apply the extension for PHP.

In the example change this:

    //Set the hostname of the mail server
    $mail->Host = 'smtp.gmail.com';

    //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission 465 ssl
    $mail->Port = 465;

    //Set the encryption system to use - ssl (deprecated) or tls
    $mail->SMTPSecure = 'ssl';

and then you recived an email from gmail talking about to enable the option to Less Safe Access Applications
here https://www.google.com/settings/security/lesssecureapps

I recommend you change the password and encrypt it constantly

answered Oct 8, 2014 at 2:03

El David's user avatar

El DavidEl David

6068 silver badges17 bronze badges

2

You’ve got no SMTPSecure setting to define the type of authentication being used, and you’re running the Host setting with the unnecessary ‘ssl://’ (PS — ssl is over port 465, if you need to run it over ssl instead, see the accepted answer here. Here’s the lines to add/change:

+ $mail->SMTPSecure = 'tls';

- $mail->Host = "ssl://smtp.gmail.com";
+ $mail->Host = "smtp.gmail.com";

Community's user avatar

answered Aug 29, 2013 at 20:58

Dmitri DB's user avatar

Dmitri DBDmitri DB

3173 silver badges15 bronze badges

4

Are you running on Localhost? and have you edit the php.ini ?

If not yet, try this:
1. Open xampp->php->php.ini
2. Search for extension=php_openssl.dll
3. The initial will look like this ;extension=php_openssl.dll
4. Remove the ‘;’ and it will look like this extension=php_openssl.dll
5. If you can’t find the extension=php_openssl.dll, add this line extension=php_openssl.dll.
6. Then restart your Xampp.

Goodluck ;)

answered Jan 11, 2014 at 4:03

Sendoh Akira's user avatar

1

I know its been a while since this question but I had the exact problem and solved it by disabling SMTP_BLOCK on csf.conf (we use CSF for a firewall).

To disable just edit csf.conf and disable SMTP_BLOCK like so:

###############################################################################
# SECTION:SMTP Settings
###############################################################################
# Block outgoing SMTP except for root, exim and mailman (forces scripts/users
# to use the exim/sendmail binary instead of sockets access). This replaces the
# protection as WHM > Tweak Settings > SMTP Tweaks
#
# This option uses the iptables ipt_owner/xt_owner module and must be loaded
# for it to work. It may not be available on some VPS platforms
#
# Note: Run /etc/csf/csftest.pl to check whether this option will function on
# this server
# SMTP_BLOCK = "1" --> this will cause phpmailer Connection timed out (110)
SMTP_BLOCK = "0"

answered Jan 23, 2016 at 20:32

Goldbug's user avatar

GoldbugGoldbug

6076 silver badges8 bronze badges

1

i’ve had this problem in tell i recive an email from google telling me that someone try to login to your account is it you and i answer yes then it start workin so if this is the case for you look in your email and allow the server

answered Jul 16, 2016 at 12:59

user5778000's user avatar

2

Login your Google account at myaccount.google.com/security go to «Login» and then «Security», scroll to bottom then enable the «Allow less secure apps» option.

Daniel's user avatar

Daniel

1,23914 silver badges24 bronze badges

answered Dec 27, 2016 at 22:07

Hieu - 7347514's user avatar

Here is a list of this you should look into when dealing with PHPMailer:

  1. Enable openSSL by un-commenting extension=php_openssl.dll in your PHP.ini
  2. Use $mail->SMTPSecure = 'tls'; and $mail->Port = 587;
  3. Enable debugging for if you are going wrong somewhere else like incorrect username and password etc.

answered May 14, 2015 at 7:02

KKK's user avatar

KKKKKK

3,1295 gold badges34 silver badges58 bronze badges

You are doing all well. Just you have to check different SMTP ports like 465 and others that works on your system.
Another thing to keep in mind to allow access to the less secure apps by google account otherwise it throws the same error.
I have gone through it for a whole day and the only thing I am doing wrong is the port no., I just changed the port no. and it works.

answered Mar 7, 2017 at 13:59

Deepak Kumar's user avatar

Deepak KumarDeepak Kumar

6771 gold badge8 silver badges22 bronze badges

Mailjet

SMTP SETTINGS

Port: 25 or 587 (some providers block port 25)

I work by changing the port after deploying the app to the server.

  • In Debug it worked for me: $mail->Port = 25;
  • In Release it worked for me: $mail->Port = 587;

GL

answered Dec 19, 2018 at 2:13

Braian Coronel's user avatar

Braian CoronelBraian Coronel

21.7k4 gold badges54 silver badges59 bronze badges

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).

answered Aug 1, 2017 at 9:19

Akif Hussain Sayyed's user avatar

If it works on your localhost but not on your web host:

Some hosting sites block certain outbound SMTP ports. Commenting out the line $mail->IsSMTP(); as noted in the accepted answer may make it work, but it is simply disabling your SMTP configuration, and using the hosting site’s email config.

If you are using GoDaddy, there is no way to send mail using a different SMTP. I was using SiteGround, and found that they were allowing SMTP access from ports 25 and 465 only, with an SSL encryption type, so I would look up documentation for your host and go from there.

answered Apr 6, 2018 at 22:06

Stephanie's user avatar

StephanieStephanie

1332 silver badges7 bronze badges

        <?php
    require 'PHPMailer/PHPMailerAutoload.php';
    
    $mail = new PHPMailer();
    
    $mail->SMTPDebug = 0;                               // Enable verbose debug output
    
    
    $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->IsSMTP();
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'mail@gmail.com';                 // SMTP username
    $mail->Password = 'your pass';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to
    $mail->setFrom('mail@gmail.com');
    $mail->addAddress('mail@gmail.com');               // Name is optional
    
    
    $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.';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        echo 'Message has been sent';
    }
    
  ?>

THIS WORK FOR ME JUST WHEN YOU WANT TO TEST
DON’T USE IDE FOR TESTING THAT BECAUSE PROBABLY NOT WORK IF YOU IN LOCALHOST USE localhost/yourfile.php

answered Mar 17, 2021 at 16:56

MAX's user avatar

the solution is configure the gmail preferences, access to no secure application

CSchulz's user avatar

CSchulz

10.8k10 gold badges59 silver badges112 bronze badges

answered Jun 6, 2016 at 3:12

marcelo's user avatar

0

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Comments

@pipesportugal

Problem description

I have been using an old version of phpmailer for many years with success (on a shared server) with the following code:
Please check http://www.crmpt.com/email_test_send_old.php

Code to reproduce

<?php
require_once("phpmailer/class.phpmailer.php");  
$mail = new PHPMailer();  
$mail->IsSMTP();  // telling the class to use SMTP  
$mail->Host     = "localhost"; // SMTP server  
$mail->SMTPAuth = true;     // turn on SMTP authentication
$mail->Username = "2e@afaturar.com";  // SMTP username
$mail->Password = "TemporaryPass123"; // SMTP password 
$mail->From = "2e@afaturar.com";
$mail->FromName = "TEST COMPANY";
$mail->AddReplyTo("ca@mz2e.com","2E");
$mail->AddCC("jose.jc.almeida@hotmail.com"); // name is optional
$mail->AddBCC("jose.jc.almeida@gmail.com");  // name is optional
$emailtosend = "ca@mz2e.com";
$mail->AddAddress("$emailtosend"); 
$mail->WordWrap = 50;                                 // set word wrap to 50 characters
$mail->IsHTML(true);                                  // set email format to HTML
$mail->Subject = "EMAIL TEST";
$mail->Body    = nl2br("EMAIL TEST ** EMAIL TEST ** EMAIL TEST **");  
$mail->AltBody = nl2br("EMAIL TEST ** EMAIL TEST ** EMAIL TEST **");

if(!$mail->Send()) {  
 echo "<br>Email not sent !!<br> ERRO: $mail->ErrorInfo<br>"; 
 echo "<br>mail->From = $mail->From<br>"; 
 echo "<br>mail->AddAddress = $emailtosend<br>"; 
}  
?>

Debug output

1 or 2 weeks ago, my provider must have changed some server settings (I don’t know) and I started receiving:
SMTP Error: Could not connect to SMTP host.

PRESENT SITUATION:

Problem description

Because of the above problem, I moved to phpmailer6, but still having no success.
please check:
http://www.crmpt.com/email_test_send_new.php

Code to reproduce

<?php
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
require 'phpmailer6/src/PHPMailer.php';
require 'phpmailer6/src/SMTP.php';
require 'phpmailer6/src/Exception.php';
$mail = new PHPMailer(true);  
try {
     $mail->SMTPDebug = 2;  
     $mail->isSMTP();  // telling the class to use SMTP  
	 $mail->Host = "mail.afaturar.com"; // SMTP server  
	 $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
     $mail->Port = 587;  
	 $mail->SMTPAuth = true;     // turn on SMTP authentication
     $mail->Username = "2e@afaturar.com";  // SMTP username
     $mail->Password = "TemporaryPass123"; // SMTP password 
	 $mail->setFrom("2e@afaturar.com");
     $emailtosendto = "ca@mz2e.com";
	 $mail->addAddress("$emailtosendto");  
     $mail->addReplyTo("ca@mz2e.com","2E");
     $mail->addCC("jose.jc.almeida@hotmail.com"); // name is optional
     $mail->addBCC("jose.jc.almeida@gmail.com");  // name is optional
     $mail->isHTML(true);                         // set email format to HTML
     $mail->Subject = "EMAIL TEST";
     $mail->Body    = nl2br("EMAIL TEST ** EMAIL TEST ** EMAIL TEST **");  
     $mail->AltBody = nl2br("EMAIL TEST ** EMAIL TEST ** EMAIL TEST **");
     $mail->send();
}
catch (Exception $e) {
    echo 'Message could not be sent(phpmailer6).<br>';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}
?>

Debug output

2017-10-29 07:00:47 SMTP ERROR: Failed to connect to server: Connection timed out (110)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Message could not be sent(phpmailer6).
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Thank you so much for all the help.
Regards
Jose.

@Synchro

Well don’t just change the code and hope it works, figure out the cause. It’s most likely that your ISP has started blocking outbound SMTP. Diagnosing this is covered in the troubleshooting guide linked from the error.

@pipesportugal

@Synchro
I have complained to my Hosting provider (vodahost) and their reply was:

Hello,

I’ve checked and could not find any issues from our end also we didn’t make any changes from our side. It seems the issue with your phpmailer script. Please check with the script from your and let me know if any changes need to be made from our end.

Regards,

The above is the configuration recommended by vodahost:

imagem

According to their instructions, I changed the following part of my code accordingly:

$mail->Host = "voda4.vodahost4.com"; // SMTP server  
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; //587 tls  

I also tested the ssl and it is loaded. Please check:
http://www.crmpt.com/teste_ssl.php

This same email is being used to send emails, without any problem from Microsoft Outlook, so if this was to be a block from vodahost on outbond SMTP, it would not be possible for Outlook to perform that task, right ?

Thanks for your help Mr Bointon,

Regards
Jose

2 participants

@Synchro

@pipesportugal

These days, an option to send mails is a basic requirement of any web application.

So popular applications like WordPress, Drupal etc. include a mail program called “PHPMailer” for sending mails.

The steps to setup PHPMailer may not be intuitive to many website owners and mistakes in configuration often cause “Smtp error: Failed to connect to server” error.

As part of our Support Services, we help website owners solve their technical issues. And, mail issue related with PHPMailer is an error that we see often .

In this article, we’ll see the top reasons for “Smtp error: Failed to connect” and how we fix them.

What is “Smtp error: Failed to connect to server” ?

Spammers often use php scripts that directly connect to remote servers and send spam mails.

To defend this, many Web Hosting providers block direct connection from websites to external mail servers.

In such servers, mails from website can be sent only via its own mail server (SMTP server) port, just as how Outlook or Windows Mail works.

PHPMailer is a mail application that works like a mail client and helps to send mail via SMTP server.

But, PHPMailer do not work out of the box. It can fail due to firewall restrictions on the server, wrong mail server name, port etc. and shows the error:

“Smtp error: Failed to connect to server”

And, depending on the response from the mail server, we’ve seen 2 variations of this error :

SMTP ERROR: Failed to connect to server: Connection refused (111)

or

SMTP ERROR: Failed to connect to server: Connection timed out (110)

What causes SMTP ERROR: Failed to connect to server ?

Here, let us discuss the top reasons for “SMTP ERROR: Failed to connect to server”.

1. SMTP restrictions on the server.

Servers restrict the programs that can directly connect to remote servers and send mail. Usually, only mail server, root user etc. allow SMTP connections.

For example, CPanel servers block access to external SMTP servers using the “SMTP Restrictions” option.

With this restriction, connection from PHPMailer to an external mail server do not work. The connection wait for some time and eventually die with the following error:

2018-10-12 04:12:37 SMTP ERROR: Failed to connect to server: Connection timed out (110)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Oops! Something went wrong and we couldn't send your message.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

2. Firewall restrictions on the server

Mail servers accept or reject connections based on certain firewall policies.

All mail servers allow the connection from default mail port 25. Bu,t other mail ports like 465, 587 etc. will not be open in many servers.

On a server with mail port restrictions, when a website owner tries to send mail using an external smtp server on port 465, it ends up in error:

2018-08-28 10:33:12 Connection: Failed to connect to server. Error number 2. "Error notice: stream_socket_client(): unable to connect to ssl://mail.xyz.com:465 (Connection refused)
2018-08-28 10:33:12 SMTP ERROR: Failed to connect to server: Connection refused (111)

Here, this “Connection Refused” error means that sending mail server refuses outbound connections on port 465 and is not able to connect to remote mail server.

3. Incorrect settings in PHPMailer

This SMTP error can also happen if the mail server name is incorrectly set (with additional white space) in PHPMailer configuration. Then, web form tries to connect to an invalid name and fails.

4. DNS failures

For the PHPMailer to work properly, the mail server specified in its configuration should have proper dns records. When dns do not work on the server, a look up from the server shows wrong IP address or no IP address for the mail server. Again, that causes mail to fail with SMTP error.

How to fix SMTP Error: Failed to connect to server

For mails to work with PHPMailer, both sending and receiving server has to accept connections.

Our Support Engineers primarily checks the connection between mail servers and find whether it is an incoming or outgoing block.

Then, to fix the mail error, we make changes on the server that includes the following :

  1. Modify the firewall rules on the server to allow outbound connections on ports like 465.
  2. Modify the SMTP restrictions on the server. Then, add particular website user to the list of users who can make outbound SMTP connections.
  3. Edit PHPMailer settings like Host, Port etc.
  4. Correct DNS resolution for mail server.

Conclusion

“SMTP ERROR: Failed to connect to server” mainly happens because of mail server connectivity issues, wrong port settings etc. Here, we have discussed the causes that our Support Engineers often see in servers and how we 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.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

I am using phpmailer to send email. It gives me an error. Here is the code

$mail = new PHPMailer();
    $mail->IsSMTP(); 
    $mail->SMTPDebug  = 2;                     
    $mail->SMTPAuth   = true;                  
    $mail->SMTPSecure = "ssl";                 
    $mail->Host       = "smtp.gmail.com";      
    $mail->Port       = 465;             
    $mail->AddAddress($email);
    $mail->Username="ajaynewnew@gmail.com";  
    $mail->Password="mypassword";
    $mail->SetFrom('user@gmail.com','name');
    $mail->AddReplyTo("user95@gmail.com"," name");
    $mail->Subject    = $subject;
    $mail->MsgHTML($message);
    $mail->Send();

asked Apr 6, 2016 at 7:30

swdpankaj's user avatar

3

try with this code

$mail = new PHPMailer(true);
$mail->IsSMTP(); 
$mail->SMTPDebug  = 2;                     
$mail->SMTPAuth   = true;                
$mail->Host       = "ssl://smtp.gmail.com";      
$mail->Port       = 465;             
$mail->AddAddress($email);
$mail->Username="ajaynewnew@gmail.com";  
$mail->Password="mypassword";
$mail->SetFrom('user@gmail.com','name');
$mail->AddReplyTo("user95@gmail.com"," name");
$mail->Subject    = $subject;
$mail->MsgHTML($message);
$mail->Send();

answered Apr 6, 2016 at 7:43

sagar patel's user avatar

sagar patelsagar patel

5915 silver badges18 bronze badges

4

Am trying to send mail to a gmail address but it keeps on getting this error «SMTP -> ERROR: Failed to connect to server: Connection timed out (110)SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed.» What could be the problem?

        require 'class.phpmailer.php'; // path to the PHPMailer class
        require 'class.smtp.php';

            $mail = new PHPMailer();


            $mail->IsSMTP();  // telling the class to use SMTP
            $mail->SMTPDebug = 2;
            $mail->Mailer = "smtp";
            $mail->Host = "ssl://smtp.gmail.com";
            $mail->Port = 587;
            $mail->SMTPAuth = true; // turn on SMTP authentication
            $mail->Username = "myemail@gmail.com"; // SMTP username
            $mail->Password = "mypasswword"; // SMTP password 
            $Mail->Priority = 1;

            $mail->AddAddress("myemail@gmail.com","Name");
            $mail->SetFrom($visitor_email, $name);
            $mail->AddReplyTo($visitor_email,$name);

            $mail->Subject  = "Message from  Contact form";
            $mail->Body     = $user_message;
            $mail->WordWrap = 50;  

            if(!$mail->Send()) {
            echo 'Message was not sent.';
            echo 'Mailer error: ' . $mail->ErrorInfo;
            } else {
            echo 'Message has been sent.';
            }

AnFi's user avatar

AnFi

10.3k3 gold badges22 silver badges46 bronze badges

asked Aug 28, 2013 at 19:29

Muli's user avatar

4

Remove or comment out the line-

$mail->IsSMTP();

And it will work for you.

I have checked and experimented many answers from different sites but haven’t got any solution except the above solution.

dario's user avatar

dario

5,11912 gold badges27 silver badges32 bronze badges

answered Aug 10, 2015 at 12:51

Snehasis's user avatar

SnehasisSnehasis

9156 silver badges10 bronze badges

17

You must to have installed php_openssl.dll, if you use wampserver it’s pretty easy, search and apply the extension for PHP.

In the example change this:

    //Set the hostname of the mail server
    $mail->Host = 'smtp.gmail.com';

    //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission 465 ssl
    $mail->Port = 465;

    //Set the encryption system to use - ssl (deprecated) or tls
    $mail->SMTPSecure = 'ssl';

and then you recived an email from gmail talking about to enable the option to Less Safe Access Applications
here https://www.google.com/settings/security/lesssecureapps

I recommend you change the password and encrypt it constantly

answered Oct 8, 2014 at 2:03

El David's user avatar

El DavidEl David

5967 silver badges16 bronze badges

2

You’ve got no SMTPSecure setting to define the type of authentication being used, and you’re running the Host setting with the unnecessary ‘ssl://’ (PS — ssl is over port 465, if you need to run it over ssl instead, see the accepted answer here. Here’s the lines to add/change:

+ $mail->SMTPSecure = 'tls';

- $mail->Host = "ssl://smtp.gmail.com";
+ $mail->Host = "smtp.gmail.com";

Community's user avatar

answered Aug 29, 2013 at 20:58

Dmitri DB's user avatar

Dmitri DBDmitri DB

3173 silver badges15 bronze badges

4

Are you running on Localhost? and have you edit the php.ini ?

If not yet, try this:
1. Open xampp->php->php.ini
2. Search for extension=php_openssl.dll
3. The initial will look like this ;extension=php_openssl.dll
4. Remove the ‘;’ and it will look like this extension=php_openssl.dll
5. If you can’t find the extension=php_openssl.dll, add this line extension=php_openssl.dll.
6. Then restart your Xampp.

Goodluck

answered Jan 11, 2014 at 4:03

Sendoh Akira's user avatar

1

I know its been a while since this question but I had the exact problem and solved it by disabling SMTP_BLOCK on csf.conf (we use CSF for a firewall).

To disable just edit csf.conf and disable SMTP_BLOCK like so:

###############################################################################
# SECTION:SMTP Settings
###############################################################################
# Block outgoing SMTP except for root, exim and mailman (forces scripts/users
# to use the exim/sendmail binary instead of sockets access). This replaces the
# protection as WHM > Tweak Settings > SMTP Tweaks
#
# This option uses the iptables ipt_owner/xt_owner module and must be loaded
# for it to work. It may not be available on some VPS platforms
#
# Note: Run /etc/csf/csftest.pl to check whether this option will function on
# this server
# SMTP_BLOCK = "1" --> this will cause phpmailer Connection timed out (110)
SMTP_BLOCK = "0"

answered Jan 23, 2016 at 20:32

Goldbug's user avatar

GoldbugGoldbug

6076 silver badges8 bronze badges

1

i’ve had this problem in tell i recive an email from google telling me that someone try to login to your account is it you and i answer yes then it start workin so if this is the case for you look in your email and allow the server

answered Jul 16, 2016 at 12:59

user5778000's user avatar

2

Login your Google account at myaccount.google.com/security go to «Login» and then «Security», scroll to bottom then enable the «Allow less secure apps» option.

Daniel's user avatar

Daniel

1,23914 silver badges24 bronze badges

answered Dec 27, 2016 at 22:07

Hieu - 7347514's user avatar

Here is a list of this you should look into when dealing with PHPMailer:

  1. Enable openSSL by un-commenting extension=php_openssl.dll in your PHP.ini
  2. Use $mail->SMTPSecure = 'tls'; and $mail->Port = 587;
  3. Enable debugging for if you are going wrong somewhere else like incorrect username and password etc.

answered May 14, 2015 at 7:02

KKK's user avatar

KKKKKK

3,1195 gold badges34 silver badges58 bronze badges

You are doing all well. Just you have to check different SMTP ports like 465 and others that works on your system.
Another thing to keep in mind to allow access to the less secure apps by google account otherwise it throws the same error.
I have gone through it for a whole day and the only thing I am doing wrong is the port no., I just changed the port no. and it works.

answered Mar 7, 2017 at 13:59

Deepak Kumar's user avatar

Deepak KumarDeepak Kumar

6621 gold badge8 silver badges22 bronze badges

Mailjet

SMTP SETTINGS

Port: 25 or 587 (some providers block port 25)

I work by changing the port after deploying the app to the server.

  • In Debug it worked for me: $mail->Port = 25;
  • In Release it worked for me: $mail->Port = 587;

GL

answered Dec 19, 2018 at 2:13

Braian Coronel's user avatar

Braian CoronelBraian Coronel

21.6k4 gold badges53 silver badges58 bronze badges

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).

answered Aug 1, 2017 at 9:19

Akif Hussain Sayyed's user avatar

If it works on your localhost but not on your web host:

Some hosting sites block certain outbound SMTP ports. Commenting out the line $mail->IsSMTP(); as noted in the accepted answer may make it work, but it is simply disabling your SMTP configuration, and using the hosting site’s email config.

If you are using GoDaddy, there is no way to send mail using a different SMTP. I was using SiteGround, and found that they were allowing SMTP access from ports 25 and 465 only, with an SSL encryption type, so I would look up documentation for your host and go from there.

answered Apr 6, 2018 at 22:06

Stephanie's user avatar

StephanieStephanie

1332 silver badges7 bronze badges

        <?php
    require 'PHPMailer/PHPMailerAutoload.php';
    
    $mail = new PHPMailer();
    
    $mail->SMTPDebug = 0;                               // Enable verbose debug output
    
    
    $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->IsSMTP();
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'mail@gmail.com';                 // SMTP username
    $mail->Password = 'your pass';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to
    $mail->setFrom('mail@gmail.com');
    $mail->addAddress('mail@gmail.com');               // Name is optional
    
    
    $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.';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        echo 'Message has been sent';
    }
    
  ?>

THIS WORK FOR ME JUST WHEN YOU WANT TO TEST
DON’T USE IDE FOR TESTING THAT BECAUSE PROBABLY NOT WORK IF YOU IN LOCALHOST USE localhost/yourfile.php

answered Mar 17, 2021 at 16:56

MAX's user avatar

the solution is configure the gmail preferences, access to no secure application

CSchulz's user avatar

CSchulz

10.7k10 gold badges59 silver badges112 bronze badges

answered Jun 6, 2016 at 3:12

marcelo's user avatar

0

Am trying to send mail to a gmail address but it keeps on getting this error «SMTP -> ERROR: Failed to connect to server: Connection timed out (110)SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed.» What could be the problem?

        require 'class.phpmailer.php'; // path to the PHPMailer class
        require 'class.smtp.php';

            $mail = new PHPMailer();


            $mail->IsSMTP();  // telling the class to use SMTP
            $mail->SMTPDebug = 2;
            $mail->Mailer = "smtp";
            $mail->Host = "ssl://smtp.gmail.com";
            $mail->Port = 587;
            $mail->SMTPAuth = true; // turn on SMTP authentication
            $mail->Username = "myemail@gmail.com"; // SMTP username
            $mail->Password = "mypasswword"; // SMTP password 
            $Mail->Priority = 1;

            $mail->AddAddress("myemail@gmail.com","Name");
            $mail->SetFrom($visitor_email, $name);
            $mail->AddReplyTo($visitor_email,$name);

            $mail->Subject  = "Message from  Contact form";
            $mail->Body     = $user_message;
            $mail->WordWrap = 50;  

            if(!$mail->Send()) {
            echo 'Message was not sent.';
            echo 'Mailer error: ' . $mail->ErrorInfo;
            } else {
            echo 'Message has been sent.';
            }

AnFi's user avatar

AnFi

10.3k3 gold badges22 silver badges46 bronze badges

asked Aug 28, 2013 at 19:29

Muli's user avatar

4

Remove or comment out the line-

$mail->IsSMTP();

And it will work for you.

I have checked and experimented many answers from different sites but haven’t got any solution except the above solution.

dario's user avatar

dario

5,11912 gold badges27 silver badges32 bronze badges

answered Aug 10, 2015 at 12:51

Snehasis's user avatar

SnehasisSnehasis

9156 silver badges10 bronze badges

17

You must to have installed php_openssl.dll, if you use wampserver it’s pretty easy, search and apply the extension for PHP.

In the example change this:

    //Set the hostname of the mail server
    $mail->Host = 'smtp.gmail.com';

    //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission 465 ssl
    $mail->Port = 465;

    //Set the encryption system to use - ssl (deprecated) or tls
    $mail->SMTPSecure = 'ssl';

and then you recived an email from gmail talking about to enable the option to Less Safe Access Applications
here https://www.google.com/settings/security/lesssecureapps

I recommend you change the password and encrypt it constantly

answered Oct 8, 2014 at 2:03

El David's user avatar

El DavidEl David

5967 silver badges16 bronze badges

2

You’ve got no SMTPSecure setting to define the type of authentication being used, and you’re running the Host setting with the unnecessary ‘ssl://’ (PS — ssl is over port 465, if you need to run it over ssl instead, see the accepted answer here. Here’s the lines to add/change:

+ $mail->SMTPSecure = 'tls';

- $mail->Host = "ssl://smtp.gmail.com";
+ $mail->Host = "smtp.gmail.com";

Community's user avatar

answered Aug 29, 2013 at 20:58

Dmitri DB's user avatar

Dmitri DBDmitri DB

3173 silver badges15 bronze badges

4

Are you running on Localhost? and have you edit the php.ini ?

If not yet, try this:
1. Open xampp->php->php.ini
2. Search for extension=php_openssl.dll
3. The initial will look like this ;extension=php_openssl.dll
4. Remove the ‘;’ and it will look like this extension=php_openssl.dll
5. If you can’t find the extension=php_openssl.dll, add this line extension=php_openssl.dll.
6. Then restart your Xampp.

Goodluck

answered Jan 11, 2014 at 4:03

Sendoh Akira's user avatar

1

I know its been a while since this question but I had the exact problem and solved it by disabling SMTP_BLOCK on csf.conf (we use CSF for a firewall).

To disable just edit csf.conf and disable SMTP_BLOCK like so:

###############################################################################
# SECTION:SMTP Settings
###############################################################################
# Block outgoing SMTP except for root, exim and mailman (forces scripts/users
# to use the exim/sendmail binary instead of sockets access). This replaces the
# protection as WHM > Tweak Settings > SMTP Tweaks
#
# This option uses the iptables ipt_owner/xt_owner module and must be loaded
# for it to work. It may not be available on some VPS platforms
#
# Note: Run /etc/csf/csftest.pl to check whether this option will function on
# this server
# SMTP_BLOCK = "1" --> this will cause phpmailer Connection timed out (110)
SMTP_BLOCK = "0"

answered Jan 23, 2016 at 20:32

Goldbug's user avatar

GoldbugGoldbug

6076 silver badges8 bronze badges

1

i’ve had this problem in tell i recive an email from google telling me that someone try to login to your account is it you and i answer yes then it start workin so if this is the case for you look in your email and allow the server

answered Jul 16, 2016 at 12:59

user5778000's user avatar

2

Login your Google account at myaccount.google.com/security go to «Login» and then «Security», scroll to bottom then enable the «Allow less secure apps» option.

Daniel's user avatar

Daniel

1,23914 silver badges24 bronze badges

answered Dec 27, 2016 at 22:07

Hieu - 7347514's user avatar

Here is a list of this you should look into when dealing with PHPMailer:

  1. Enable openSSL by un-commenting extension=php_openssl.dll in your PHP.ini
  2. Use $mail->SMTPSecure = 'tls'; and $mail->Port = 587;
  3. Enable debugging for if you are going wrong somewhere else like incorrect username and password etc.

answered May 14, 2015 at 7:02

KKK's user avatar

KKKKKK

3,1195 gold badges34 silver badges58 bronze badges

You are doing all well. Just you have to check different SMTP ports like 465 and others that works on your system.
Another thing to keep in mind to allow access to the less secure apps by google account otherwise it throws the same error.
I have gone through it for a whole day and the only thing I am doing wrong is the port no., I just changed the port no. and it works.

answered Mar 7, 2017 at 13:59

Deepak Kumar's user avatar

Deepak KumarDeepak Kumar

6621 gold badge8 silver badges22 bronze badges

Mailjet

SMTP SETTINGS

Port: 25 or 587 (some providers block port 25)

I work by changing the port after deploying the app to the server.

  • In Debug it worked for me: $mail->Port = 25;
  • In Release it worked for me: $mail->Port = 587;

GL

answered Dec 19, 2018 at 2:13

Braian Coronel's user avatar

Braian CoronelBraian Coronel

21.6k4 gold badges53 silver badges58 bronze badges

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).

answered Aug 1, 2017 at 9:19

Akif Hussain Sayyed's user avatar

If it works on your localhost but not on your web host:

Some hosting sites block certain outbound SMTP ports. Commenting out the line $mail->IsSMTP(); as noted in the accepted answer may make it work, but it is simply disabling your SMTP configuration, and using the hosting site’s email config.

If you are using GoDaddy, there is no way to send mail using a different SMTP. I was using SiteGround, and found that they were allowing SMTP access from ports 25 and 465 only, with an SSL encryption type, so I would look up documentation for your host and go from there.

answered Apr 6, 2018 at 22:06

Stephanie's user avatar

StephanieStephanie

1332 silver badges7 bronze badges

        <?php
    require 'PHPMailer/PHPMailerAutoload.php';
    
    $mail = new PHPMailer();
    
    $mail->SMTPDebug = 0;                               // Enable verbose debug output
    
    
    $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->IsSMTP();
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'mail@gmail.com';                 // SMTP username
    $mail->Password = 'your pass';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to
    $mail->setFrom('mail@gmail.com');
    $mail->addAddress('mail@gmail.com');               // Name is optional
    
    
    $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.';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        echo 'Message has been sent';
    }
    
  ?>

THIS WORK FOR ME JUST WHEN YOU WANT TO TEST
DON’T USE IDE FOR TESTING THAT BECAUSE PROBABLY NOT WORK IF YOU IN LOCALHOST USE localhost/yourfile.php

answered Mar 17, 2021 at 16:56

MAX's user avatar

the solution is configure the gmail preferences, access to no secure application

CSchulz's user avatar

CSchulz

10.7k10 gold badges59 silver badges112 bronze badges

answered Jun 6, 2016 at 3:12

marcelo's user avatar

0

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Comments

@pipesportugal

Problem description

I have been using an old version of phpmailer for many years with success (on a shared server) with the following code:
Please check http://www.crmpt.com/email_test_send_old.php

Code to reproduce

<?php
require_once("phpmailer/class.phpmailer.php");  
$mail = new PHPMailer();  
$mail->IsSMTP();  // telling the class to use SMTP  
$mail->Host     = "localhost"; // SMTP server  
$mail->SMTPAuth = true;     // turn on SMTP authentication
$mail->Username = "2e@afaturar.com";  // SMTP username
$mail->Password = "TemporaryPass123"; // SMTP password 
$mail->From = "2e@afaturar.com";
$mail->FromName = "TEST COMPANY";
$mail->AddReplyTo("ca@mz2e.com","2E");
$mail->AddCC("jose.jc.almeida@hotmail.com"); // name is optional
$mail->AddBCC("jose.jc.almeida@gmail.com");  // name is optional
$emailtosend = "ca@mz2e.com";
$mail->AddAddress("$emailtosend"); 
$mail->WordWrap = 50;                                 // set word wrap to 50 characters
$mail->IsHTML(true);                                  // set email format to HTML
$mail->Subject = "EMAIL TEST";
$mail->Body    = nl2br("EMAIL TEST ** EMAIL TEST ** EMAIL TEST **");  
$mail->AltBody = nl2br("EMAIL TEST ** EMAIL TEST ** EMAIL TEST **");

if(!$mail->Send()) {  
 echo "<br>Email not sent !!<br> ERRO: $mail->ErrorInfo<br>"; 
 echo "<br>mail->From = $mail->From<br>"; 
 echo "<br>mail->AddAddress = $emailtosend<br>"; 
}  
?>

Debug output

1 or 2 weeks ago, my provider must have changed some server settings (I don’t know) and I started receiving:
SMTP Error: Could not connect to SMTP host.

PRESENT SITUATION:

Problem description

Because of the above problem, I moved to phpmailer6, but still having no success.
please check:
http://www.crmpt.com/email_test_send_new.php

Code to reproduce

<?php
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
require 'phpmailer6/src/PHPMailer.php';
require 'phpmailer6/src/SMTP.php';
require 'phpmailer6/src/Exception.php';
$mail = new PHPMailer(true);  
try {
     $mail->SMTPDebug = 2;  
     $mail->isSMTP();  // telling the class to use SMTP  
	 $mail->Host = "mail.afaturar.com"; // SMTP server  
	 $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
     $mail->Port = 587;  
	 $mail->SMTPAuth = true;     // turn on SMTP authentication
     $mail->Username = "2e@afaturar.com";  // SMTP username
     $mail->Password = "TemporaryPass123"; // SMTP password 
	 $mail->setFrom("2e@afaturar.com");
     $emailtosendto = "ca@mz2e.com";
	 $mail->addAddress("$emailtosendto");  
     $mail->addReplyTo("ca@mz2e.com","2E");
     $mail->addCC("jose.jc.almeida@hotmail.com"); // name is optional
     $mail->addBCC("jose.jc.almeida@gmail.com");  // name is optional
     $mail->isHTML(true);                         // set email format to HTML
     $mail->Subject = "EMAIL TEST";
     $mail->Body    = nl2br("EMAIL TEST ** EMAIL TEST ** EMAIL TEST **");  
     $mail->AltBody = nl2br("EMAIL TEST ** EMAIL TEST ** EMAIL TEST **");
     $mail->send();
}
catch (Exception $e) {
    echo 'Message could not be sent(phpmailer6).<br>';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}
?>

Debug output

2017-10-29 07:00:47 SMTP ERROR: Failed to connect to server: Connection timed out (110)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Message could not be sent(phpmailer6).
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Thank you so much for all the help.
Regards
Jose.

@Synchro

Well don’t just change the code and hope it works, figure out the cause. It’s most likely that your ISP has started blocking outbound SMTP. Diagnosing this is covered in the troubleshooting guide linked from the error.

@pipesportugal

@Synchro
I have complained to my Hosting provider (vodahost) and their reply was:

Hello,

I’ve checked and could not find any issues from our end also we didn’t make any changes from our side. It seems the issue with your phpmailer script. Please check with the script from your and let me know if any changes need to be made from our end.

Regards,

The above is the configuration recommended by vodahost:

imagem

According to their instructions, I changed the following part of my code accordingly:

$mail->Host = "voda4.vodahost4.com"; // SMTP server  
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; //587 tls  

I also tested the ssl and it is loaded. Please check:
http://www.crmpt.com/teste_ssl.php

This same email is being used to send emails, without any problem from Microsoft Outlook, so if this was to be a block from vodahost on outbond SMTP, it would not be possible for Outlook to perform that task, right ?

Thanks for your help Mr Bointon,

Regards
Jose

2 participants

@Synchro

@pipesportugal

These days, an option to send mails is a basic requirement of any web application.

So popular applications like WordPress, Drupal etc. include a mail program called “PHPMailer” for sending mails.

The steps to setup PHPMailer may not be intuitive to many website owners and mistakes in configuration often cause “Smtp error: Failed to connect to server” error.

As part of our Support Services, we help website owners solve their technical issues. And, mail issue related with PHPMailer is an error that we see often .

In this article, we’ll see the top reasons for “Smtp error: Failed to connect” and how we fix them.

What is “Smtp error: Failed to connect to server” ?

Spammers often use php scripts that directly connect to remote servers and send spam mails.

To defend this, many Web Hosting providers block direct connection from websites to external mail servers.

In such servers, mails from website can be sent only via its own mail server (SMTP server) port, just as how Outlook or Windows Mail works.

PHPMailer is a mail application that works like a mail client and helps to send mail via SMTP server.

But, PHPMailer do not work out of the box. It can fail due to firewall restrictions on the server, wrong mail server name, port etc. and shows the error:

“Smtp error: Failed to connect to server”

And, depending on the response from the mail server, we’ve seen 2 variations of this error :

SMTP ERROR: Failed to connect to server: Connection refused (111)

or

SMTP ERROR: Failed to connect to server: Connection timed out (110)

What causes SMTP ERROR: Failed to connect to server ?

Here, let us discuss the top reasons for “SMTP ERROR: Failed to connect to server”.

1. SMTP restrictions on the server.

Servers restrict the programs that can directly connect to remote servers and send mail. Usually, only mail server, root user etc. allow SMTP connections.

For example, CPanel servers block access to external SMTP servers using the “SMTP Restrictions” option.

With this restriction, connection from PHPMailer to an external mail server do not work. The connection wait for some time and eventually die with the following error:

2018-10-12 04:12:37 SMTP ERROR: Failed to connect to server: Connection timed out (110)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Oops! Something went wrong and we couldn't send your message.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

2. Firewall restrictions on the server

Mail servers accept or reject connections based on certain firewall policies.

All mail servers allow the connection from default mail port 25. Bu,t other mail ports like 465, 587 etc. will not be open in many servers.

On a server with mail port restrictions, when a website owner tries to send mail using an external smtp server on port 465, it ends up in error:

2018-08-28 10:33:12 Connection: Failed to connect to server. Error number 2. "Error notice: stream_socket_client(): unable to connect to ssl://mail.xyz.com:465 (Connection refused)
2018-08-28 10:33:12 SMTP ERROR: Failed to connect to server: Connection refused (111)

Here, this “Connection Refused” error means that sending mail server refuses outbound connections on port 465 and is not able to connect to remote mail server.

3. Incorrect settings in PHPMailer

This SMTP error can also happen if the mail server name is incorrectly set (with additional white space) in PHPMailer configuration. Then, web form tries to connect to an invalid name and fails.

4. DNS failures

For the PHPMailer to work properly, the mail server specified in its configuration should have proper dns records. When dns do not work on the server, a look up from the server shows wrong IP address or no IP address for the mail server. Again, that causes mail to fail with SMTP error.

How to fix SMTP Error: Failed to connect to server

For mails to work with PHPMailer, both sending and receiving server has to accept connections.

Our Support Engineers primarily checks the connection between mail servers and find whether it is an incoming or outgoing block.

Then, to fix the mail error, we make changes on the server that includes the following :

  1. Modify the firewall rules on the server to allow outbound connections on ports like 465.
  2. Modify the SMTP restrictions on the server. Then, add particular website user to the list of users who can make outbound SMTP connections.
  3. Edit PHPMailer settings like Host, Port etc.
  4. Correct DNS resolution for mail server.

Conclusion

“SMTP ERROR: Failed to connect to server” mainly happens because of mail server connectivity issues, wrong port settings etc. Here, we have discussed the causes that our Support Engineers often see in servers and how we 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.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Hi,

Last week, PHPMailer suddenly stopped working. I got the following as the error message when I send the test e-mail:

SMTP -> ERROR: Failed to connect to server: Connection timed out (110)
SMTP Error: Could not connect to SMTP host.

I’ve found the same issue with the module SMTP Authentication Support.

Any idea what could have caused this? Any good suggestions for debugging this?

Tag1 supports the Drupal Project.Tag1 logo

Comments

smk-ka’s picture

Connection time-out means the mail server cannot be reached anymore. If the mail server is different from your web server (i.e. not localhost) I’d check with your hosting provider whether they enabled some sort of firewall that blocks connections on the SMTP port (port 25 usually).

  • Log in or register to post comments

Relia’s picture

Hello I have the same problem.

I set up PHPMailer to send mails trought gmail:

Primary SMTP server:mail.gbt.tfo.upm.es
SMTP Port: 465
Use secure protocol: SSL

User: usergmail@gmail.com
password: gmailpassword

TEst configuration: mailtutest@domain.com

But when I submit clickin save configuration, the next error message appear:

A test e-mail has been sent to fjpeces@gfgf.es. You may want to check the logs for any error messages.
SMTP -> ERROR: Failed to connect to server: Connection timed out (110)
SMTP Error: Could not connect to SMTP host.

I’m using OpenSuSe 10.3, Server Apache2, php 5.2.5.

I think the problem is the ports are closed to outside, but before to communicate with the admin, i’d want read your opinions!

thanks!

  • Log in or register to post comments

LEternity’s picture

I contacted my provider and they fixed the problem. I.e. they screwed up…

  • Log in or register to post comments

Relia’s picture

i fixed the problem, I cotacted admin and the problem was the ports! They are closed!

  • Log in or register to post comments

smk-ka’s picture

Thanks for your feedback, I’ve added a description for this error to README.txt, based on what I said in #1.

  • Log in or register to post comments
Status: Fixed » Closed (fixed)

Automatically closed — issue fixed for 2 weeks with no activity.

  • Log in or register to post comments

ThirstySix’s picture

In localhost SMTP work’s fine, but , site it does not work SMTP.
I give same configuration in SMTP localhost and site.

but I get below error

SMTP -> ERROR: Failed to connect to server: Connection timed out (111)
SMTP Error: Could not connect to SMTP host. 

I changed port number and name….etc..
but i get same error….
how can I slove this?

Thanks in advance..

  • Log in or register to post comments

smk-ka’s picture

@satheeshkumarr Read comment #1. Contact your hosting provider to open specific firewall ports.

  • Log in or register to post comments

Mahadirz’s picture

Version: 6.x-2.1 » 7.x-3.x-dev
Component: Code » Miscellaneous
Status: Closed (fixed) » Active

I also got this same problem before…
Try checking all your files and directories permission. If all your files and folder permission is set to 777 they can’t access to SMTP config.

So reset the permission of all the files to 644 while the folders to 755 .

cheers…
http://www.mahadirlab.com/en

  • Log in or register to post comments

zabalex’s picture

I had the same issue with my host. They told me to try every possible option, stated that it was a problem with my code, email server, application (drupal), etc.
I wasted 2 weeks, than hired a guy to develop firewall ports blocking detection application, and here it is. As soon as I was able to proove to hosting company that they blocked port 465, they did not admin problem. As soon as I showed them this tool, yes, they admitted that they have problem and opened the port.
Here is the tool: Port forwarding tester external server:

Let me know what you think

  • Log in or register to post comments

earth1’s picture

@smk-ka #1. I am using PHPMailer 6.x-2.2. Firewall is not the answer.

error -> SMTP error: could not connect to SMTP host.

The website is using godaddy with jangosmtp as it email system. It’s Primary SMTP server: relay.jangostmp.net and SMTP port: 587. The godaddy representative said go to my MX (Mail Exchanger) and set relay.jangostmp.net. But this didn’t work. I am running out of ideas. Can you help me?

Thanks in advance

  • Log in or register to post comments

zabalex’s picture

I spent so much time on issues like that, I might be able to help you Earth1 if the tool from my previous post doesn’t show port as blocked.
Don’t trust their advise on MX Exchanger. I prooved back to GoDaddy that over 50% of popular organizations don’t set their relays, and their emails still go through fine.
What is your domain? Send me PM if you don’t want to list it here.

  • Log in or register to post comments

keithm’s picture

This problem may be a result of enabling IPv6 support in the operating system. I saw several sites with working PHPMailer configurations break when my host enabled IPv6. PHP has multiple known bugs in dealing with IPv6.

PHPMailer uses the PHP fsockopen() function that has this known bug.

The problem is that fsockopen() doesn’t detect that a connection was actively refused and instead times out on it.

The problem scenario occurs when the host has both ipv4 and ipv6 addresses (e.g,, smtp.gmail.com), the service is only listening on ipv4 but ipv6 has precedence, which results in:

  1. trying IPv6
  2. time out
  3. fail

instead of:

  1. trying IPv6
  2. connection refused
  3. trying IPv4
  4. success

If this is the problem, you can work around it by setting the IP address directly in the PHPMailer settings or in /etc/hosts. The problem still exists (at least) in PHP v5.3.2.

  • Log in or register to post comments

vvenk’s picture

Hi:

I am on a Windows 7 machine and developing an application that has SendEmail as a function using VB.Net and MS Visual Studio 2010.

The code works fine on another Windows 7 machine. The only difference is that the laptop it does not work is a corporate laptop and I am part of the Administrators group on that laptop.

I used the tool and it says the port is open.

Any idea how to resolve the issue?

venki

  • Log in or register to post comments

ravi_dev’s picture

I have another mail server for my site then how can i connect ‘@fsockopen(«www.google.com», 80, $errno, $errstr, 10)’?

  • Log in or register to post comments

Anonymous’s picture

Comment #16

Anonymous (not verified) CreditAttribution: Anonymous commented 7 October 2016 at 08:14

This error is not resolving check the image after saving smtp configuration this screen appears

  • Log in or register to post comments

oadaeh’s picture

Comment #17

oadaeh CreditAttribution: oadaeh as a volunteer commented 7 October 2016 at 13:21

Status: Active » Closed (won’t fix)

@saif-ur-rehman, that error is not from this module, but from the Variable module. You need to start there to resolve the problem. And next time, open a new issue, as this one you posted on is unrelated.

  • Log in or register to post comments

oadaeh’s picture

Comment #18

oadaeh CreditAttribution: oadaeh as a volunteer commented 7 October 2016 at 13:25

@saif-ur-rehman, allow me to clarify what I said about starting a new issue. What you did in searching for an existing issue to post in was a good thing, but the issue you ended up posting in was unrelated to your problem, and so you should have just created a new issue.

  • Log in or register to post comments

oadaeh’s picture

Comment #19

oadaeh CreditAttribution: oadaeh as a volunteer commented 7 October 2016 at 13:26

Status: Closed (won’t fix) » Fixed

I set the wrong status previously, so now I’m fixing that.

  • Log in or register to post comments

oadaeh’s picture

Comment #20

oadaeh CreditAttribution: oadaeh as a volunteer commented 7 October 2016 at 13:26

Status: Fixed » Closed (fixed)
  • Log in or register to post comments

thanhseouc’s picture

My site is not a bug fix as above not overcome

  • Log in or register to post comments

oadaeh’s picture

  • Log in or register to post comments

Skip to content

  • Hello there,

    I am no longer receiving emails from a plugin Quiz and Survey Master QSM. I asked my hosting company letshost, email provider Office 365 and the QSM plugin provider about this but they said to contact WordPress as it seems to be a problem with latest WordPress or PHP verison update.

    Error in Easy WP SMTP Test email:

    SMTP ERROR: Failed to connect to server: Connection timed out (110)SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshootinghttps://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

    Has anyone come across this lately?

    WordPress 5.7.2 running Twenty Eleven theme.

    Easy WP SMTP SET UP:
    SMTP Host:smtp.office365.com
    Type of Encryption: STARTTLS
    SMTP Port:587

    Thank you,

    The page I need help with: [log in to see the link]

  • The topic ‘SMTP ERROR: Failed to connect to server: Connection timed out (110)SMTP connect(’ is closed to new replies.

Проблема — скорее две несвязанные проблемы — то, что вы испытываете, довольно проста:

ОШИБКА SMTP: Не удалось подключиться к серверу: время ожидания подключения (110) Ошибка SMTP connect().

и вы подтвердили, что сервер действительно принимает соединения:

Я попытался подключиться к SMTP-серверу с помощью команды telnet

Last login: Fri Sep 16 11:08:06 on ttys000
admin:~ admin$ telnet mail.example.in 25
Trying 111.91.153.112...
Connected to mail.example.in.

Ваш script не может подключиться к SMTP-серверу при запуске с его производственного сервера.

Вероятная причина заключается в том, что сервер производства имеет брандмауэр, который во избежание злоупотреблений предотвращает любое подключение к внешней стороне. Сервер может обслуживать веб-запросы, но не более.

Если ваш тест подтвердил, что порт 25 не отвечает, то (после проверки правильности адреса хоста) вы могли бы попробовать telnet mail.example.in 587 вместо. Если это сработало, это могло означать, что сервер не принимает небезопасные соединения (порт 25), но принимает безопасные соединения. С помощью PHPMailer вы могли бы попробовать активировать безопасное соединение:

$mail->SMTPSecure = 'tls';

или

$mail->SMTPSecure = 'ssl';

Если это не сработает, у вас может быть проблема с брандмауэром; или вам может потребоваться посмотреть phpinfo() и убедиться, что у вас есть поддержка OpenSSL, доступная в PHP.

Что вам нужно сделать

  • попросите ИТ-специалистов, которые поддерживают производственный сервер, открыть брандмауэр;
  • более перспективно, спросите их, как отправлять электронные письма с этого сервера. Скорее всего, вам нужно использовать функцию mail() или использовать localhost или 127.0.0.1 как SMTP-сервер. Затем электронные письма будут отправляться через вашу сервисную сеть вашего производственного сервера.

Они могут сказать вам, что порт 25 не разрешен, но разрешен порт (скажем) 465 или 567. Вам необходимо будет обновить свою конфигурацию и/или добавить TLS/SSL соответственно (см. Выше).

  • или вам может быть позволено подключиться к стороннему SMTP-серверу, которому вы должны будете предоставить IP-адрес, чтобы позволить ИТ-ребятам открыть соответствующее окно брандмауэра. Затем электронные письма будут отправляться через сторонний сервер.

Вторая проблема (возможно, НЕ проблема)

250 [email protected] Отправитель OK RCPT: [email protected] 554 Реле отклонено по политическим причинам.

Кроме того, чтобы избежать злоупотреблений, SMTP-серверы не позволят каждому подключаться и отправлять электронные письма, но только их собственные клиенты. Я вижу, что в конфигурации PHPMailer вы указали пользователя и пароль. В сеансе telnet вы этого не сделали. Поэтому вполне возможно, что PHPmailer может отправлять, но не подключаться, в то время как ваш telnet может подключаться, но не отправлять.

Как только вы решите проблему подключения, проблема аутентификации будет решена или исчезнет (потому что вы будете использовать другой сервер, предоставленный вам ИТ-ребятами, например localhost).

Третья проблема (может никогда не возникнуть)

Третий способ злоупотребления услугами — чрезмерное использование — отправка слишком большого количества сообщений электронной почты слишком многим людям. Проверьте с ИТ-ребятами, какие приемлемые политики предназначены для отправки писем.

Проблемы, проблемы

Другие вещи, на которые нужно обратить внимание, — это достоверность источника (вы можете отправить электронные письма от имени какого-либо домена, который не определил ваш SMTP-сервер в качестве разрешенного отправителя) и конфиденциальность данных (даже с TLS/SSL, если вам предоставлен localhost в качестве SMTP-сервера, ваши ИТ-ребята будут иметь полный, неограниченный, необнаруживаемый доступ к любому отправляемому вами электронному адресу. Возможно, вы можете или не можете быть в порядке).

Проблема — скорее две несвязанные проблемы — то, что вы испытываете, довольно проста:

ОШИБКА SMTP: Не удалось подключиться к серверу: время ожидания подключения (110) Ошибка SMTP connect().

и вы подтвердили, что сервер действительно принимает соединения:

Я попытался подключиться к SMTP-серверу с помощью команды telnet

Last login: Fri Sep 16 11:08:06 on ttys000
admin:~ admin$ telnet mail.example.in 25
Trying 111.91.153.112...
Connected to mail.example.in.

Ваш script не может подключиться к SMTP-серверу при запуске с его производственного сервера.

Вероятная причина заключается в том, что сервер производства имеет брандмауэр, который во избежание злоупотреблений предотвращает любое подключение к внешней стороне. Сервер может обслуживать веб-запросы, но не более.

Если ваш тест подтвердил, что порт 25 не отвечает, то (после проверки правильности адреса хоста) вы могли бы попробовать telnet mail.example.in 587 вместо. Если это сработало, это могло означать, что сервер не принимает небезопасные соединения (порт 25), но принимает безопасные соединения. С помощью PHPMailer вы могли бы попробовать активировать безопасное соединение:

$mail->SMTPSecure = 'tls';

или

$mail->SMTPSecure = 'ssl';

Если это не сработает, у вас может быть проблема с брандмауэром; или вам может потребоваться посмотреть phpinfo() и убедиться, что у вас есть поддержка OpenSSL, доступная в PHP.

Что вам нужно сделать

  • попросите ИТ-специалистов, которые поддерживают производственный сервер, открыть брандмауэр;
  • более перспективно, спросите их, как отправлять электронные письма с этого сервера. Скорее всего, вам нужно использовать функцию mail() или использовать localhost или 127.0.0.1 как SMTP-сервер. Затем электронные письма будут отправляться через вашу сервисную сеть вашего производственного сервера.

Они могут сказать вам, что порт 25 не разрешен, но разрешен порт (скажем) 465 или 567. Вам необходимо будет обновить свою конфигурацию и/или добавить TLS/SSL соответственно (см. Выше).

  • или вам может быть позволено подключиться к стороннему SMTP-серверу, которому вы должны будете предоставить IP-адрес, чтобы позволить ИТ-ребятам открыть соответствующее окно брандмауэра. Затем электронные письма будут отправляться через сторонний сервер.

Вторая проблема (возможно, НЕ проблема)

250 [email protected] Отправитель OK RCPT: [email protected] 554 Реле отклонено по политическим причинам.

Кроме того, чтобы избежать злоупотреблений, SMTP-серверы не позволят каждому подключаться и отправлять электронные письма, но только их собственные клиенты. Я вижу, что в конфигурации PHPMailer вы указали пользователя и пароль. В сеансе telnet вы этого не сделали. Поэтому вполне возможно, что PHPmailer может отправлять, но не подключаться, в то время как ваш telnet может подключаться, но не отправлять.

Как только вы решите проблему подключения, проблема аутентификации будет решена или исчезнет (потому что вы будете использовать другой сервер, предоставленный вам ИТ-ребятами, например localhost).

Третья проблема (может никогда не возникнуть)

Третий способ злоупотребления услугами — чрезмерное использование — отправка слишком большого количества сообщений электронной почты слишком многим людям. Проверьте с ИТ-ребятами, какие приемлемые политики предназначены для отправки писем.

Проблемы, проблемы

Другие вещи, на которые нужно обратить внимание, — это достоверность источника (вы можете отправить электронные письма от имени какого-либо домена, который не определил ваш SMTP-сервер в качестве разрешенного отправителя) и конфиденциальность данных (даже с TLS/SSL, если вам предоставлен localhost в качестве SMTP-сервера, ваши ИТ-ребята будут иметь полный, неограниченный, необнаруживаемый доступ к любому отправляемому вами электронному адресу. Возможно, вы можете или не можете быть в порядке).

Hi,

Last week, PHPMailer suddenly stopped working. I got the following as the error message when I send the test e-mail:

SMTP -> ERROR: Failed to connect to server: Connection timed out (110)
SMTP Error: Could not connect to SMTP host.

I’ve found the same issue with the module SMTP Authentication Support.

Any idea what could have caused this? Any good suggestions for debugging this?

Tag1 supports the Drupal Project.Tag1 logo

Comments

smk-ka’s picture

Connection time-out means the mail server cannot be reached anymore. If the mail server is different from your web server (i.e. not localhost) I’d check with your hosting provider whether they enabled some sort of firewall that blocks connections on the SMTP port (port 25 usually).

  • Log in or register to post comments

Relia’s picture

Hello I have the same problem.

I set up PHPMailer to send mails trought gmail:

Primary SMTP server:mail.gbt.tfo.upm.es
SMTP Port: 465
Use secure protocol: SSL

User: usergmail@gmail.com
password: gmailpassword

TEst configuration: mailtutest@domain.com

But when I submit clickin save configuration, the next error message appear:

A test e-mail has been sent to fjpeces@gfgf.es. You may want to check the logs for any error messages.
SMTP -> ERROR: Failed to connect to server: Connection timed out (110)
SMTP Error: Could not connect to SMTP host.

I’m using OpenSuSe 10.3, Server Apache2, php 5.2.5.

I think the problem is the ports are closed to outside, but before to communicate with the admin, i’d want read your opinions!

thanks!

  • Log in or register to post comments

LEternity’s picture

I contacted my provider and they fixed the problem. I.e. they screwed up…

  • Log in or register to post comments

Relia’s picture

i fixed the problem, I cotacted admin and the problem was the ports! They are closed!

  • Log in or register to post comments

smk-ka’s picture

Thanks for your feedback, I’ve added a description for this error to README.txt, based on what I said in #1.

  • Log in or register to post comments
Status: Fixed » Closed (fixed)

Automatically closed — issue fixed for 2 weeks with no activity.

  • Log in or register to post comments

ThirstySix’s picture

In localhost SMTP work’s fine, but , site it does not work SMTP.
I give same configuration in SMTP localhost and site.

but I get below error

SMTP -> ERROR: Failed to connect to server: Connection timed out (111)
SMTP Error: Could not connect to SMTP host. 

I changed port number and name….etc..
but i get same error….
how can I slove this?

Thanks in advance..

  • Log in or register to post comments

smk-ka’s picture

@satheeshkumarr Read comment #1. Contact your hosting provider to open specific firewall ports.

  • Log in or register to post comments

Mahadirz’s picture

Version: 6.x-2.1 » 7.x-3.x-dev
Component: Code » Miscellaneous
Status: Closed (fixed) » Active

I also got this same problem before…
Try checking all your files and directories permission. If all your files and folder permission is set to 777 they can’t access to SMTP config.

So reset the permission of all the files to 644 while the folders to 755 .

cheers…
http://www.mahadirlab.com/en

  • Log in or register to post comments

zabalex’s picture

I had the same issue with my host. They told me to try every possible option, stated that it was a problem with my code, email server, application (drupal), etc.
I wasted 2 weeks, than hired a guy to develop firewall ports blocking detection application, and here it is. As soon as I was able to proove to hosting company that they blocked port 465, they did not admin problem. As soon as I showed them this tool, yes, they admitted that they have problem and opened the port.
Here is the tool: Port forwarding tester external server:

Let me know what you think

  • Log in or register to post comments

earth1’s picture

@smk-ka #1. I am using PHPMailer 6.x-2.2. Firewall is not the answer.

error -> SMTP error: could not connect to SMTP host.

The website is using godaddy with jangosmtp as it email system. It’s Primary SMTP server: relay.jangostmp.net and SMTP port: 587. The godaddy representative said go to my MX (Mail Exchanger) and set relay.jangostmp.net. But this didn’t work. I am running out of ideas. Can you help me?

Thanks in advance

  • Log in or register to post comments

zabalex’s picture

I spent so much time on issues like that, I might be able to help you Earth1 if the tool from my previous post doesn’t show port as blocked.
Don’t trust their advise on MX Exchanger. I prooved back to GoDaddy that over 50% of popular organizations don’t set their relays, and their emails still go through fine.
What is your domain? Send me PM if you don’t want to list it here.

  • Log in or register to post comments

keithm’s picture

This problem may be a result of enabling IPv6 support in the operating system. I saw several sites with working PHPMailer configurations break when my host enabled IPv6. PHP has multiple known bugs in dealing with IPv6.

PHPMailer uses the PHP fsockopen() function that has this known bug.

The problem is that fsockopen() doesn’t detect that a connection was actively refused and instead times out on it.

The problem scenario occurs when the host has both ipv4 and ipv6 addresses (e.g,, smtp.gmail.com), the service is only listening on ipv4 but ipv6 has precedence, which results in:

  1. trying IPv6
  2. time out
  3. fail

instead of:

  1. trying IPv6
  2. connection refused
  3. trying IPv4
  4. success

If this is the problem, you can work around it by setting the IP address directly in the PHPMailer settings or in /etc/hosts. The problem still exists (at least) in PHP v5.3.2.

  • Log in or register to post comments

vvenk’s picture

Hi:

I am on a Windows 7 machine and developing an application that has SendEmail as a function using VB.Net and MS Visual Studio 2010.

The code works fine on another Windows 7 machine. The only difference is that the laptop it does not work is a corporate laptop and I am part of the Administrators group on that laptop.

I used the tool and it says the port is open.

Any idea how to resolve the issue?

venki

  • Log in or register to post comments

ravi_dev’s picture

I have another mail server for my site then how can i connect ‘@fsockopen(«www.google.com», 80, $errno, $errstr, 10)’?

  • Log in or register to post comments

Anonymous’s picture

Comment #16

Anonymous (not verified) CreditAttribution: Anonymous commented 7 October 2016 at 08:14

This error is not resolving check the image after saving smtp configuration this screen appears

  • Log in or register to post comments

oadaeh’s picture

Comment #17

oadaeh CreditAttribution: oadaeh as a volunteer commented 7 October 2016 at 13:21

Status: Active » Closed (won’t fix)

@saif-ur-rehman, that error is not from this module, but from the Variable module. You need to start there to resolve the problem. And next time, open a new issue, as this one you posted on is unrelated.

  • Log in or register to post comments

oadaeh’s picture

Comment #18

oadaeh CreditAttribution: oadaeh as a volunteer commented 7 October 2016 at 13:25

@saif-ur-rehman, allow me to clarify what I said about starting a new issue. What you did in searching for an existing issue to post in was a good thing, but the issue you ended up posting in was unrelated to your problem, and so you should have just created a new issue.

  • Log in or register to post comments

oadaeh’s picture

Comment #19

oadaeh CreditAttribution: oadaeh as a volunteer commented 7 October 2016 at 13:26

Status: Closed (won’t fix) » Fixed

I set the wrong status previously, so now I’m fixing that.

  • Log in or register to post comments

oadaeh’s picture

Comment #20

oadaeh CreditAttribution: oadaeh as a volunteer commented 7 October 2016 at 13:26

Status: Fixed » Closed (fixed)
  • Log in or register to post comments

thanhseouc’s picture

My site is not a bug fix as above not overcome

  • Log in or register to post comments

oadaeh’s picture

  • Log in or register to post comments

I am getting SMTP Error with PHP Mailer and Outlook SMTP. I am confused here because it is working fine on localhost with Port number 25 but It is not working on Hosting Server, I have tried all ports with SSL & TLS.

Error : SMTP ERROR: Failed to connect to server: Connection timed out (110)

My Code:

<?php

include("PHPMailer.php"); 

error_reporting(E_ALL);
ini_set('display_errors', '1');

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "smtp.live.com";
$mail->SMTPDebug = 2;
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Username = "info@neelcomputech.com";
$mail->Password = "password";
$mail->Priority    = 1;
$mail->CharSet     = 'UTF-8';
$mail->ContentType = 'text/html; charset=utf-8rn';

$mail->From = "info@neelcomputech.com";
$mail->FromName = $name;
$mail->AddAddress("info@neelcomputech.com");

$mail->IsHTML(true);

$mail->Subject = "You got Message from Website";
$mail->Body = "testing";

if(!$mail->Send())
{
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}
else
{
    echo 'success';
}

?>

Please help me to solve this issue. I have Shared Linux Hosting.

Понравилась статья? Поделить с друзьями:
  • Ошибка пневмы на туареге
  • Ошибка подключения к серверу sedo fss ru
  • Ошибка пневмы е53
  • Ошибка печати 16389 0х00004005
  • Ошибка пламени бакси слим