Извините, если это дорога, по которой много ездили. Я видел другие посты об этом, но ничто в них не решило проблему, которую я имею, или зажгло лампочку, которая помогла мне решить это самостоятельно.
Вот мой код:
require 'PHPMailerAutoload.php';
$config = parse_ini_file('/path/to/file/config.ini', true);
$mail = new PHPMailer;
$mail->SMTPDebug = 3;
$mail->Debugoutput = 'html';
$mail->isSMTP();
$mail->Host = $config['host']; //smtp.office365.com
$mail->SMTPAuth = true;
$mail->Username = $config['username']; //an.existing.account@appinc.co
$mail->Password = $config['password']; //confirmed this is being passed correctly
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->From = $config['username'];
$mail->FromName = 'Website Forms';
$mail->addAddress('sales@appinc.co', 'Some Name');
$mail->addReplyTo('sender.email@somedomain.com', 'SenderFirst SenderLast');
$mail->addBCC('my.email.address@appinc.co');
$mail->isHTML(true);
$mail->Subject = 'Contact Form Submission';
$mail->Body = 'Some html here';
$mail->AltBody = 'Some alt content here';
if(!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
//perform success actions
exit();
}
Я подтвердил, что домен, имя пользователя и пароль верны и передаются правильно. Важно отметить, что это работало на нашем локальном сервере разработчика до запуска. Как только сайт был перенесен на наш хостинг-аккаунт (Hostgator), это когда он перестал работать. Я подтвердил с помощью HG, что порт 587 открыт на нашем сервере.
Вот сообщение об ошибке, которое я вижу:
Connection: opening to smtp.office365.com:587, t=10, opt=array ()
SMTP ERROR: Failed to connect to server: Connection refused (111)
SMTP connect() failed.
Message could not be sent.Mailer Error: SMTP connect() failed.
Любая помощь, которая может быть оказана, очень ценится, даже если это просто ссылка на статью, которая объясняет, почему она не будет работать сейчас, когда она находится в нашей производственной среде.
8
Решение
Ни один из ответов не сработал для меня.
Через много часов я нашел проблему, но работает только для Cpanel / WHM
- Войдите в WHM.
- Перейти к ConfigServer Security & Брандмауэр внутри плагина опция.
- Нажмите на настройку брандмауэра
- Фильтр по настройкам SMTP
- Найдите параметр SMTP_ALLOWUSER и добавьте имя пользователя учетной записи Cpanel, разделенное комой.
- Перезагрузите брандмауэр.
Если у вас нет доступа к WHM, обратитесь к своему провайдеру.
6
Другие решения
В PHP 5.5 и phpmailer есть ошибка с номером порта. Не устанавливайте номер порта (mail-> port = ….), это вызывает ошибку:
msgstr «ошибка smtp не удалось установить соединение с сервером отказано 111»
Оставьте номер порта по умолчанию 25, и он будет работать!
2
Оказывается, HG нужно было изменить настройки брандмауэра на нашем сервере. Как только они это сделали, все заработало отлично. Так что, если у вас возникла подобная проблема, я бы порекомендовал убедиться, что все правильно с вашей стороны, но затем посоветуйтесь с вашим хостинг-провайдером, чтобы узнать, что нужно сделать с их стороны.
0
Если вы используете cPanel / WHM, вам необходимо убедиться, что:
Ограничить исходящий SMTP для root, exim и mailman (FKA SMTP Tweak) — установлен в OFF. (Это можно отредактировать в разделе «Конфигурация сервера» Настройки твика (поиск: SMTP))
Если у вас также есть ConfigServer Security & Брандмауэр включен, вам нужно будет изменить конфигурацию брандмауэра. Нажмите «Настройка брандмауэра», затем выберите «Фильтровать по настройкам SMTP». Теперь найдите SMTP_ALLOWUSER и добавьте имя пользователя учетной записи cPanel, разделенное комой. Нажмите «Изменить» и перезапустите брандмауэр.
0
Есть 3 сервера.
1 mailwizz -web программа для отправки писем
2 mailwizz -web программа для отправки писем
3 почтовый сервер
оба mailwiz — по конфигурации вроде как идентичны
на почтовом сервере 587 порт открыт, ограничений на mailwizz сервера нет, все в порядке
mailwizz,ы подключаются к почтовому серверу через smtp
почтовым сервером управляет PMTA, сертификаты настроены — другой майлвиз шлет
проблема:
1 mailwizz — прекрасно коннектится по 587 к почтовому серверу и шлет письма
2 mailwizz — не как не хочет, пишет ошибку
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Connection: opening to m-spf.ru:587, timeout=30, options=array ( 'ssl' => array ( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true, ),)
Connection failed. Error #2: stream_socket_client(): unable to connect to postal.ru:587 (Connection refused) [/var/www/mailwizz/data/www/mailwizz.ru/apps/common/vendors/Composer/vendor/phpmailer/phpmailer/src/SMTP.php line 387]
SMTP ERROR: Failed to connect to server: Connection refused (111)
на проблемном сервере mailwizz
— панель isp manager
— PHP Version 7.3.19
— SSL Version OpenSSL/1.0.2u
openssl
OpenSSL support enabled
OpenSSL Library Version OpenSSL 1.1.0l 10 Sep 2019
OpenSSL Header Version OpenSSL 1.1.0l 10 Sep 2019
Openssl default config /usr/lib/ssl/openssl.cnf
Native OpenSSL support enabled
все что про него знаю, вроде тоже самое что на другом mailwizz
Как можно мой майлвиз подружить с 587 портом моего почтового сервера.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 |
<?php /** * SendMailSmtpClass * * Класс для отправки писем через SMTP с авторизацией * Может работать через SSL протокол * Тестировалось на почтовых серверах yandex.ru, mail.ru и gmail.com * * @author Ipatov Evgeniy <admin@ipatov-soft.ru> * @version 1.0 */ class SendMailSmtpClass { /** * * @var string $smtp_username - логин * @var string $smtp_password - пароль * @var string $smtp_host - хост * @var string $smtp_from - от кого * @var integer $smtp_port - порт * @var string $smtp_charset - кодировка * */ public $smtp_username; public $smtp_password; public $smtp_host; public $smtp_from; public $smtp_port; public $smtp_charset; public function __construct($smtp_username, $smtp_password, $smtp_host, $smtp_from, $smtp_port = 25, $smtp_charset = "utf-8") { $this->smtp_username = $smtp_username; $this->smtp_password = $smtp_password; $this->smtp_host = $smtp_host; $this->smtp_from = $smtp_from; $this->smtp_port = $smtp_port; $this->smtp_charset = $smtp_charset; } /** * Отправка письма * * @param string $mailTo - получатель письма * @param string $subject - тема письма * @param string $message - тело письма * @param string $headers - заголовки письма * * @return bool|string В случаи отправки вернет true, иначе текст ошибки * */ function send($mailTo, $subject, $message, $headers) { $contentMail = "Date: " . date("D, d M Y H:i:s") . " UTrn"; $contentMail .= 'Subject: =?' . $this->smtp_charset . '?B?' . base64_encode($subject) . "=?=rn"; $contentMail .= $headers . "rn"; $contentMail .= $message . "rn"; try { if(!$socket = @fsockopen($this->smtp_host, $this->smtp_port, $errorNumber, $errorDescription, 30)){ throw new Exception($errorNumber.".".$errorDescription); } if (!$this->_parseServer($socket, "220")){ throw new Exception('Connection error'); } $server_name = $_SERVER["SERVER_NAME"]; fputs($socket, "HELO $server_namern"); if (!$this->_parseServer($socket, "250")) { fclose($socket); throw new Exception('Error of command sending: HELO'); } fputs($socket, "AUTH LOGINrn"); if (!$this->_parseServer($socket, "334")) { fclose($socket); throw new Exception('Autorization error'); } fputs($socket, base64_encode($this->smtp_username) . "rn"); if (!$this->_parseServer($socket, "334")) { fclose($socket); throw new Exception('Autorization error'); } fputs($socket, base64_encode($this->smtp_password) . "rn"); if (!$this->_parseServer($socket, "235")) { fclose($socket); throw new Exception('Autorization error'); } fputs($socket, "MAIL FROM: <".$this->smtp_username.">rn"); if (!$this->_parseServer($socket, "250")) { fclose($socket); throw new Exception('Error of command sending: MAIL FROM'); } $mailTo = ltrim($mailTo, '<'); $mailTo = rtrim($mailTo, '>'); fputs($socket, "RCPT TO: <" . $mailTo . ">rn"); if (!$this->_parseServer($socket, "250")) { fclose($socket); throw new Exception('Error of command sending: RCPT TO'); } fputs($socket, "DATArn"); if (!$this->_parseServer($socket, "354")) { fclose($socket); throw new Exception('Error of command sending: DATA'); } fputs($socket, $contentMail."rn.rn"); if (!$this->_parseServer($socket, "250")) { fclose($socket); throw new Exception("E-mail didn't sent"); } fputs($socket, "QUITrn"); fclose($socket); } catch (Exception $e) { return $e->getMessage(); } return true; } private function _parseServer($socket, $response) { while (@substr($responseServer, 3, 1) != ' ') { if (!($responseServer = fgets($socket, 256))) { return false; } } if (!(substr($responseServer, 0, 3) == $response)) { return false; } return true; } } |
I’m new to PHPMailer, and I just downloaded it with Composer and coded this as index.php:
<?php
require_once 'vendor/autoload.php';
use PHPMailerPHPMailerPHPMailer;
$m = new PHPMailer;
$m->isSMTP();
$m->SMTPAuth = true;
$m->SMTPDebug = 2;
$m->Host = 'smtp.mail.yahoo.com';
$m->Username = 'vagefipooya@yahoo.com';
$m->Password = 'MY PASSWORD';
$m->SMTPSecure = 'ssl';
$m->Port = 465;
$m->IsHTML(true);
$m->SetFrom('pouyavey@gmail.com');
$m->FromName = 'Pouya Vaghefi';
$m->addReplyTo('pouyavey@gmail.com','Pouya Vey');
$m->addAddress('pouyavey@gmail.com','Pouya Vey');
//$m->addCC('alex@phpacademy','Alex Garret');
//$m->addBCC('alex@phpacademy','Alex Garret');
$m->CharSet = "UTF-8";
$m->Subject = 'Here is an email';
$m->msgHTML("convert HTML into a basic plain-text alternative body");
$m->Body = 'This is the body of an email';
$m->AltBody = 'This is the body of an email';
if (!$m->send()) {
echo "Mailer Error: " . $m->ErrorInfo;
} else {
echo "Message sent!";
}
?>
Then I uploaded it to my site (my site does not use ssl) which is using cPanel and tried to load the page but I got this as error:
2018-04-19 10:03:46 SMTP ERROR: Failed to connect to server: Connection refused (111)
SMTP connect() failed. /wiki/Troubleshooting
Mailer Error: SMTP connect() failed.
I also read the related questions to this problem and changed the port from 465 to 587 (with tls), 25 and 26 but couldn’t solve the problem yet.
So can you please help me with this error, cause I really don’t know what to do!
Thanks…
asked Apr 19, 2018 at 10:08
4
This is mostly due to your hosting providers firewall issues. See on below link where someone had similar issue —
https://github.com/PHPMailer/PHPMailer/issues/295
Contact your hosting provider, they will be able to help you
answered Apr 23, 2018 at 13:31
mdeoramdeora
3,9502 gold badges16 silver badges29 bronze badges
I tried your code with my email and token, also not work, it shows :
2018-04-28 13:52:41 SMTP ERROR: Failed to connect to server: (0)
2018-04-28 13:52:41 SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
then i changed below two lines:
$m->SMTPSecure = 'ssl';
$m->Port = 465;
to
$m->SMTPSecure = 'tls';
$m->Port = 587;
then, it works
...
2018-04-28 13:53:13 SERVER -> CLIENT: 354 Start mail input; end with <CRLF>.<CRLF>
2018-04-28 13:53:13 CLIENT -> SERVER: Date: Sat, 28 Apr 2018 21:53:04 +0800
2018-04-28 13:53:13 CLIENT -> SERVER: To: "feiffy" <example@example.com>
2018-04-28 13:53:13 CLIENT -> SERVER: From: feiffy <feifeifanye@hotmail.com>
2018-04-28 13:53:13 CLIENT -> SERVER: Reply-To: "feiffy" <example@example.com>
2018-04-28 13:53:13 CLIENT -> SERVER: Subject: Here is an email
2018-04-28 13:53:13 CLIENT -> SERVER: Message-ID: <hW4npgJlHQ2CjCqR42xK7j7BRpAzEFAz8mnwK4G6o@pc>
2018-04-28 13:53:13 CLIENT -> SERVER: X-Mailer: PHPMailer 6.0.5 (https://github.com/PHPMailer/PHPMailer)
2018-04-28 13:53:13 CLIENT -> SERVER: MIME-Version: 1.0
2018-04-28 13:53:13 CLIENT -> SERVER: Content-Type: multipart/alternative;
2018-04-28 13:53:13 CLIENT -> SERVER: boundary="b1_hW4npgJlHQ2CjCqR42xK7j7BRpAzEFAz8mnwK4G6o"
2018-04-28 13:53:13 CLIENT -> SERVER: Content-Transfer-Encoding: 8bit
2018-04-28 13:53:13 CLIENT -> SERVER:
2018-04-28 13:53:13 CLIENT -> SERVER: This is a multi-part message in MIME format.
2018-04-28 13:53:13 CLIENT -> SERVER: --b1_hW4npgJlHQ2CjCqR42xK7j7BRpAzEFAz8mnwK4G6o
2018-04-28 13:53:13 CLIENT -> SERVER: Content-Type: text/plain; charset=us-ascii
2018-04-28 13:53:13 CLIENT -> SERVER:
2018-04-28 13:53:13 CLIENT -> SERVER: This is the body of an email
2018-04-28 13:53:13 CLIENT -> SERVER:
2018-04-28 13:53:13 CLIENT -> SERVER: --b1_hW4npgJlHQ2CjCqR42xK7j7BRpAzEFAz8mnwK4G6o
2018-04-28 13:53:13 CLIENT -> SERVER: Content-Type: text/html; charset=us-ascii
2018-04-28 13:53:13 CLIENT -> SERVER:
2018-04-28 13:53:13 CLIENT -> SERVER: This is the body of an email
2018-04-28 13:53:13 CLIENT -> SERVER:
2018-04-28 13:53:13 CLIENT -> SERVER:
2018-04-28 13:53:13 CLIENT -> SERVER: --b1_hW4npgJlHQ2CjCqR42xK7j7BRpAzEFAz8mnwK4G6o--
2018-04-28 13:53:13 CLIENT -> SERVER:
2018-04-28 13:53:13 CLIENT -> SERVER: .
2018-04-28 13:53:14 SERVER -> CLIENT: 250 2.0.0 OK <hW4npgJlHQ2CjCqR42xK7j7BRpAzEFAz8mnwK4G6o@pc> [Hostname=SG2PR06MB0776.apcprd06.prod.outlook.com]
2018-04-28 13:53:14 CLIENT -> SERVER: QUIT
2018-04-28 13:53:14 SERVER -> CLIENT: 221 2.0.0 Service closing transmission channel
hope to help you.
answered Apr 28, 2018 at 14:07
![]()
I’ve been using mailgun and I love it. Mailgun.com Totally free for a case like this.
As a suggestion, can you see if there’s a sendmail daemon running on your box? Maybe that will be good enough for your use case?
answered Apr 25, 2018 at 21:35
LucasLucas
4613 silver badges7 bronze badges
1
I want to send mail using phpmailer. I have uploaded my phpmailer files on my Godaddy server. The below code is running in my localhost but not on my server.
2019-02-03 16:54:12 SMTP ERROR: Failed to connect to server: Connection refused (111)
The below is the code for php
<?php
include_once('PHPMailer/src/PHPMailer.php');
include_once('PHPMailer/src/SMTP.php');
$mail = new PHPMailerPHPMailerPHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587,465
$mail->IsHTML(true);
$mail->Username = "mail@gmail.com";
$mail->Password = "password";
$mail->SetFrom("mail@gmail.com");
$mail->Subject = "Test mail";
$mail->Body = "Hello World";
$mail->AddAddress("mail@gmail.com");
if($mail->Send()) {
echo "Message has been sent";
}
?>
![]()
James Z
12.2k10 gold badges28 silver badges44 bronze badges
asked Feb 3, 2019 at 17:07
![]()
5
use PHPMailerPHPMailerPHPMailer; <-- make sure these are not in a function
use PHPMailerPHPMailerException;
require 'path/src/Exception.php';
require 'path/src/PHPMailer.php';
require 'path/src/SMTP.php';
Use tls and not ssl it can be buggy
$mail->SMTPSecure = "tls";
$mail->Port = 587;
Check out my answer here this will tell you everything you need to know to connect to gmail with phpmailer
answered Feb 3, 2019 at 18:34
![]()
Cesar BielichCesar Bielich
4,6749 gold badges38 silver badges77 bronze badges
18
I want to send mail using phpmailer. I have uploaded my phpmailer files on my Godaddy server. The below code is running in my localhost but not on my server.
2019-02-03 16:54:12 SMTP ERROR: Failed to connect to server: Connection refused (111)
The below is the code for php
<?php
include_once('PHPMailer/src/PHPMailer.php');
include_once('PHPMailer/src/SMTP.php');
$mail = new PHPMailerPHPMailerPHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587,465
$mail->IsHTML(true);
$mail->Username = "mail@gmail.com";
$mail->Password = "password";
$mail->SetFrom("mail@gmail.com");
$mail->Subject = "Test mail";
$mail->Body = "Hello World";
$mail->AddAddress("mail@gmail.com");
if($mail->Send()) {
echo "Message has been sent";
}
?>
![]()
James Z
12.2k10 gold badges28 silver badges44 bronze badges
asked Feb 3, 2019 at 17:07
![]()
5
use PHPMailerPHPMailerPHPMailer; <-- make sure these are not in a function
use PHPMailerPHPMailerException;
require 'path/src/Exception.php';
require 'path/src/PHPMailer.php';
require 'path/src/SMTP.php';
Use tls and not ssl it can be buggy
$mail->SMTPSecure = "tls";
$mail->Port = 587;
Check out my answer here this will tell you everything you need to know to connect to gmail with phpmailer
answered Feb 3, 2019 at 18:34
![]()
Cesar BielichCesar Bielich
4,6749 gold badges38 silver badges77 bronze badges
18
Sometimes users need to send outgoing e-mails with external SMTP servers. Most popular example is PHPMailer with its ability to use free SMTP servers, for example Gmail. Here is the short piece of code, that allows to do this:
<?php
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
require './mail/PHPMailer-master/src/Exception.php';
require './PHPMailer-master/src/PHPMailer.php';
require './mail/PHPMailer-master/src/SMTP.php';
date_default_timezone_set('Etc/UTC');
$milo="this is a test";
/**
* This example shows sending a message using PHP's mail() function.
*/
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
$mail->SMTPDebug = 0;
//Set who the message is to be sent from
$mail->setFrom('example@gmail.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('support@example.com', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer test 2 smtp';
$mail->CharSet = 'UTF-8';
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
$mail->SMTPSecure = 'tls';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = "example@gmail.com";
//Password to use for SMTP authentication
$mail->Password = "yourpassword";
$mail->msgHTML($milo);
//Replace the plain text body with one created manually
$mail->AltBody = $milo;
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
If you have a Directadmin server with csf firewall installed, most probably you will get this message on execution:
SMTP ERROR: Failed to connect to server: Connection refused (111)
Let’s investigate what causes this error. First, we need to change debug level in our script to get all error messages:
$mail->SMTPDebug = 4;
Here is what we are getting:
2018-03-29 13:01:34 Connection: opening to smtp.gmail.com:587, timeout=300, options=array() 2018-03-29 13:01:37 Connection failed. Error #2: stream_socket_client(): unable to connect to smtp.gmail.com:587 (Connection refused) [SMTP.php line 326] 2018-03-29 13:01:37 SMTP ERROR: Failed to connect to server: Connection refused (111) SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
So the problem seems to be with opening port 587 – the script is even unable to connect. Let’s verify if we have this port blocked by firewall:
[root@server ~]# dmesg | grep 587
Most probably our output will look like this:
Firewall: *TCP_OUT Blocked* IN= OUT=eth0 SRC=62.210.90.101 DST=66.102.1.109 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=57285 DF PROTO=TCP SPT=50856 DPT=587 WINDOW=14600 RES=0x00 SYN URGP=0 UID=503 GID=505 Firewall: *TCP6OUT Blocked* IN= OUT=eth0 SRC=fe80:0000:0000:0000:fabc:12ff:fe48:effa DST=2a00:1450:400c:0c06:0000:0000:0000:006d LEN=80 TC=0 HOPLIMIT=64 FLOWLBL=0 PROTO=TCP SPT=45138 DPT=587 WINDOW=14400 RES=0x00 SYN URGP=0 UID=503 GID=505 Firewall: *TCP6OUT Blocked* IN= OUT=eth0 SRC=fe80:0000:0000:0000:fabc:12ff:fe48:effa DST=2a00:1450:400c:0c06:0000:0000:0000:006d LEN=80 TC=0 HOPLIMIT=64 FLOWLBL=0 PROTO=TCP SPT=45138 DPT=587 WINDOW=14400 RES=0x00 SYN URGP=0 UID=503 GID=505
Here’s the catch – our firewall is blocking outgoing connection through this port. We need to unlock it to continue. Here is the solution.
Open /etc/csf/csf.conf in any editor
Scroll to this line:
SMTP_BLOCK = "1"
Change it to
SMTP_BLOCK = "0"
Restart csf:
csf -r
Now you should be able to use your script without any issues.
Sorry if this is a road heavily traveled. I’ve seen the other posts about this but nothing in them has either solved the problem I’m having or ignited a lightbulb that helped me solve it myself.
Here’s my code:
require 'PHPMailerAutoload.php';
$config = parse_ini_file('/path/to/file/config.ini', true);
$mail = new PHPMailer;
$mail->SMTPDebug = 3;
$mail->Debugoutput = 'html';
$mail->isSMTP();
$mail->Host = $config['host']; //smtp.office365.com
$mail->SMTPAuth = true;
$mail->Username = $config['username']; //an.existing.account@appinc.co
$mail->Password = $config['password']; //confirmed this is being passed correctly
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->From = $config['username'];
$mail->FromName = 'Website Forms';
$mail->addAddress('sales@appinc.co', 'Some Name');
$mail->addReplyTo('sender.email@somedomain.com', 'SenderFirst SenderLast');
$mail->addBCC('my.email.address@appinc.co');
$mail->isHTML(true);
$mail->Subject = 'Contact Form Submission';
$mail->Body = 'Some html here';
$mail->AltBody = 'Some alt content here';
if(!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
//perform success actions
exit();
}
I’ve confirmed that the domain, username and password are all correct and being passed in correctly. Important to note that this worked on our local dev server prior to launch. Once the site was moved to our hosting account (Hostgator) is when it stopped working. I’ve confirmed with HG that port 587 is open on our server.
Here is the error message I’m seeing:
Connection: opening to smtp.office365.com:587, t=10, opt=array ()
SMTP ERROR: Failed to connect to server: Connection refused (111)
SMTP connect() failed.
Message could not be sent.Mailer Error: SMTP connect() failed.
Any help that can be provided is very much appreciated, even if it’s just a link to an article that explains why it won’t work now that it’s in our production environment.
[EDIT]: Minor grammatical error.
This sounds like a network/sysadmin problem, not a PHPMailer problem. Try a
telnet smtp.office365.com 587
in your console, for checking conectivity. If everything is working ok, it should write a message like ‘ESMTP MAIL Service ready’. Otherwise that server is blocking yours.
@drmad Thanks!
I’ve checked the 587 ports on both servers — mine and smtp.office365.com — with telnet and nmap. They both appear to be open and responding. Because I’m on a shared hosting account (Hostgator, cPanel), I don’t have terminal access on my web server (that I can find), unless you know some way for me to run the telnet remotely. Sorry, I’m not very versed in telnet usage.
Here’s the response from telnet to smtp.office365.com:
Trying 132.245.81.178...
Connected to outlook-namsouth.office365.com.
Escape character is '^]'.
220 BY2PR06CA037.outlook.office365.com Microsoft ESMTP MAIL Service ready at Sun, 12 Oct 2014 00:38:36 +0000
And here is the response from my host server:
Trying 192.254.235.140...
Connected to appinc.co.
Escape character is '^]'.
220-gator3253.hostgator.com ESMTP Exim 4.82 #2 Sat, 11 Oct 2014 19:39:34 -0500
220-We do not authorize the use of this system to transport unsolicited,
220 and/or bulk e-mail.
Thanks in advanced for any extra help you can provide.
Perhaps office365.com is blocking your hostgator server. The fastest (and easiest) way is creating a support ticket in hostgator for they to check that conectivity issue.
You say you have no terminal access to your server, so I’m guessing those examples you posted are done from somewhere else so the fact that you can get to them doesn’t mean that you can from your hostgator server. It could also be a DNS issue on your hostgator config.
Thanks for the advice @Synchro. I contacted HG, again, and asked them about the DNS and could there be anything in the firewall that would be blocking outbound traffic. Sure enough, it was the firewall. They made a change and now it works great! Really appreciate your and @drmad’s help!
Glad you sorted that out.
Thanks bro..i will try that ))
@ndub did u get solution regarding above matter?
Read the guide the error links to.
hello @ndub , @drmad , @Synchro @hargrig ,
##ERROR is
SMTP ERROR: Failed to connect to server: Connection refused (111)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
is is work on local host but once i run on godaddy server i can’t and error shot . plz solve and sugges me
**## My Code HTML is **«<style type=»text/css»>
/form/label { position: absolute; -webkit-transform: translateY(6px); transform: translateY(6px); left: 13px; color: rgb(0, 0, 0); -webkit-transition: all 0.25s ease; transition: all 0.25s ease; pointer-events: none; font-size: 19px; font-family: "century gothic"; } label .req { margin: 2px; color: #b11a1a; } label.active { -webkit-transform: translateY(50px); transform: translateY(50px); left: 2px; font-size: 14px; top: -70px; } label.active .req { opacity: 1; } label.highlight { color: #000; } input, textarea { font-size: 17px; display: block; width: 100%; padding: 5px 10px; background: none; background-image: none; border: 1px solid #a0b3b0; color: #000; border-radius: 0; -webkit-transition: border-color .25s ease, box-shadow .25s ease; transition: border-color .25s ease, box-shadow .25s ease; } input:focus, textarea:focus { outline: 0; border-color: #b11a1a; } textarea { border: 2px solid #a0b3b0; resize: vertical; height: 120px; } .field-wrap { position: relative; margin-bottom: 30px; } .top-row:after { content: ""; display: table; clear: both; } .top-row>div { float: left; width: 48%; margin-right: 4%; } .top-row>div:last-child { margin: 0; } .button { border: 0; outline: none; border-radius: 0; padding: 10px 0; font-size: 1rem; font-weight: 600; text-transform: uppercase; letter-spacing: .1em; background: #b11a1a; color: #ffffff; -webkit-transition: all 0.5s ease; transition: all 0.5s ease; -webkit-appearance: none; } .button:hover, .button:focus { background: #9b1717; } .button-block { display: block; width: 100%; } .forgot { margin-top: -20px; text-align: right; } .content { padding-bottom: 0px; } * { font-family: 'Century Gothic' !important; }</style>
Register and get more information
<br> <form action="mail.php" method="POST" id="form"> <input type="email" id="email" name="owneremail" maxlength="30" placeholder="enter email address to get user data " style="margin-bottom:30px"> <div class="top-row"> <div class="field-wrap"> <label class="active highlight"> First Name<span class="req">*</span> </label> <input type="text" pattern="[a-zA-Z]{3,30}" id="fname" name="fname" maxlength="30"> </div> <div class="field-wrap"> <label class="active highlight"> Last Name<span class="req">*</span> </label> <input type="text" pattern="[a-zA-Z]{3,30}" id="lname" name="lname" maxlength="30"> </div> </div> <div class="field-wrap"> <label class="active highlight"> Company name<span class="req">*</span> </label> <input type="text" class="half" name="company" id="cname"> </div> <div class="top-row"> <div class="field-wrap"> <label class="active highlight"> City<span class="req">*</span> </label> <input type="text" pattern="[a-zA-Z]{3,20}" name="city" id="city"> </div> <div class="field-wrap"> <label class="active highlight"> State/Province<span class="req">*</span> </label> <input type="text" pattern="[a-zA-Z]{3,20}" name="state" id="province"> </div> </div> <div class="top-row"> <div class="field-wrap"> <label class="active highlight"> Email Address<span class="req">*</span> </label> <input type="email" required="required" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,3}$" name="email" id="memail"> </div> <div class="field-wrap"> <label class="active highlight"> Phone<span class="req">*</span> </label> <input type="number" autocomplete="on" pattern="[0-9]{10,15}" name="phone" id="mobile"> </div> </div> <div class="field-wrap"> <label class="active highlight"> Website<span class="req">*</span> </label> <input type="text" class="half" pattern="[a-zA-Z._-%^]" name="website" id="website" value=""> </div> <div class="field-wrap"> <label class="active highlight"> Queries </label> <textarea name="queries" autocomplete="off"></textarea> </div> <button type="submit" value="Submit" name="Submit" class="button button-block">Send</button> </form>My PHP Code is
/form/
SMTPDebug = 3;
$mail->Debugoutput = ‘html’;
$mail->isSMTP();
$mail->Host = ‘ssl://smtp.gmail.com’;
$mail->SMTPAuth = true;
$mail->Username = ‘useremailaddress@gmail.com’;
$mail->Password = ‘userpassword’;
$mail->SMTPSecure = ‘ssl’;
$mail->Port = 465;
$mail->isHTML(true);
$mail->From = ‘useremailaddress@gmail.com’;
$mail->FromName = ‘this is test’;
$mail->addAddress($email_to);
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->Subject = ‘ASK FOR A DEMO’;
$mail->Body = ‘hello’;
if(!$mail->send()) {
echo ‘Message could not be sent.’;
echo ‘Mailer Error: ‘ . $mail->ErrorInfo;
} else {
echo ‘Message has been sent’;
echo «<script>alert(‘».$email_to.» thank you!’);</script>»;
}
}
?>hello
You see that link to the troubleshooting guide? Click it, and read what it says about GoDaddy.
PHPMailer
locked as resolved and limited conversation to collaborators
Jan 18, 2019