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:
use PHPMailer\PHPMailer\PHPMailer; |
use PHPMailer\PHPMailer\Exception; |
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' ); |
$mail ->setFrom( 'example@gmail.com' , 'First Last' ); |
$mail ->addAddress( 'support@example.com' , 'John Doe' ); |
$mail ->Subject = 'PHPMailer test 2 smtp' ; |
$mail ->CharSet = 'UTF-8' ; |
$mail ->Debugoutput = 'html' ; |
$mail ->SMTPSecure = 'tls' ; |
$mail ->Host = 'smtp.gmail.com' ; |
$mail ->Username = "example@gmail.com" ; |
$mail ->Password = "yourpassword" ; |
echo "Mailer Error: " . $mail ->ErrorInfo; |
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:
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 |
2018-03-29 13:01:37 SMTP ERROR: Failed to connect to server: Connection refused (111) |
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:
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:
Change it to
Restart csf:
Now you should be able to use your script without any issues.