Меню

Phpmailer ошибка smtp connect failed

You are missing the directive that states the connection uses SSL

require ("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); 
$mail->SMTPAuth = true;     // turn of SMTP authentication
$mail->Username = "YAHOO ACCOUNT";  // SMTP username
$mail->Password = "YAHOO ACCOUNT PASSWORD"; // SMTP password
$mail->SMTPSecure = "ssl";
$mail->Host = "YAHOO HOST"; // SMTP host
$mail->Port = 465;

Then add in the other parts

$webmaster_email = "myemail@gmail.com";       //Reply to this email ID
$email="myyahoomail@yahoo.in";                // Recipients email ID
$name="My Name";                              // Recipient's name
$mail->From = $webmaster_email;
$mail->FromName = "My Name";
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,"My Name");
$mail->WordWrap = 50;                         // set word wrap
$mail->IsHTML(true);                          // send as HTML
$mail->Subject = "subject";
$mail->Body = "Hi,
This is the HTML BODY ";                      //HTML Body 
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body 

if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}

As a side note, I have had trouble using Body + AltBody together although they are supposed to work. As a result, I wrote the following wrapper function which works perfectly.

<?php
require ("class.phpmailer.php");

// Setup Configuration for Mail Server Settings
$email['host']          = 'smtp.email.com';
$email['port']          = 366;
$email['user']          = 'from@email.com';
$email['pass']          = 'from password';
$email['from']          = 'From Name';
$email['reply']         = 'replyto@email.com';
$email['replyname']     = 'Reply To Name';

$addresses_to_mail_to = 'email1@email.com;email2@email.com';
$email_subject = 'My Subject';
$email_body = '<html>Code Here</html>';
$who_is_receiving_name = 'John Smith';

$result = sendmail(
    $email_body,
    $email_subject,
    $addresses_to_mail_to,
    $who_is_receiving_name
);

var_export($result);


function sendmail($body, $subject, $to, $name, $attach = "") {

  global $email;
  $return = false;

  $mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
  $mail->IsSMTP(); // telling the class to use SMTP
  try {
    $mail->Host       = $email['host']; // SMTP server
//    $mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
    $mail->SMTPAuth   = true;                  // enable SMTP authentication
    $mail->Host       = $email['host']; // sets the SMTP server
    $mail->Port       = $email['port'];                    // set the SMTP port for the GMAIL server
    $mail->SMTPSecure = "tls";
    $mail->Username   = $email['user']; // SMTP account username
    $mail->Password   = $email['pass'];        // SMTP account password
    $mail->AddReplyTo($email['reply'], $email['replyname']);
    if(stristr($to,';')) {
      $totmp = explode(';',$to);
      foreach($totmp as $destto) {
        if(trim($destto) != "") {
          $mail->AddAddress(trim($destto), $name);
        }
      }
    } else {
      $mail->AddAddress($to, $name);
    }
    $mail->SetFrom($email['user'], $email['from']);
    $mail->Subject = $subject;
    $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
    $mail->MsgHTML($body);
    if(is_array($attach)) {
        foreach($attach as $attach_f) {
            if($attach_f != "") {
              $mail->AddAttachment($attach_f);      // attachment
            }
        }
    } else {
        if($attach != "") {
          $mail->AddAttachment($attach);      // attachment
        }
    }
    $mail->Send();
  } catch (phpmailerException $e) {
    $return = $e->errorMessage();
  } catch (Exception $e) {
    $return = $e->errorMessage();
  }

  return $return;
}

@ErfanImmortal

i have problem with PHPmailer and get
Message could not be sent.Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Debug output

<?php

// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;

require 'PHPmailer/src/Exception.php';
require 'PHPmailer/src/PHPMailer.php';
require 'PHPmailer/src/SMTP.php';
$mail = new PHPMailer;                              // Passing `true` enables exceptions


    //Server settings
	$mail->isSMTP();                                      // Set mailer to use SMTP
	$mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'arzaangift@gmail.com';                 // SMTP username
    $mail->Password = '**********';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to
    //Recipients
    $mail->setFrom('admin@marveliptv.com', 'Marvel IPTV');
    $mail->addAddress('karyab13052@gmail.com');     // Add a recipient
    $mail->addReplyTo('marvelteam.sup@gmail.com');
    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Salam' ;

	$mailContent = '
<h2>Eri</h2>
<p>Eri</p>
<p>Eri</p>';

    $mail->Body    = $mailContent ;
    $mail->send();

if(!$mail->send()){
    echo 'Message could not be sent.';
    echo 'Error: '. $mail->ErrorInfo;
}else{
	echo 'Message has been sent';
}	

?>

@Synchro

Please follow the link to the troubleshooting guide in the error message which gives details of how to diagnose this exact problem.

@ErfanImmortal

2019-02-28 12:00:46 Connection: opening to smtp.gmail.com:587, timeout=300, options=array()
2019-02-28 12:00:47 Connection failed. Error #2: stream_socket_client(): unable to connect to smtp.gmail.com:587 (Network is unreachable) [/home/marvemhc/public_html/lab2/PHPmailer/src/SMTP.php line 327]
2019-02-28 12:00:47 SMTP ERROR: Failed to connect to server: Network is unreachable (101)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
2019-02-28 12:00:47 Connection: opening to smtp.gmail.com:587, timeout=300, options=array()
2019-02-28 12:00:48 Connection failed. Error #2: stream_socket_client(): unable to connect to smtp.gmail.com:587 (Network is unreachable) [/home/marvemhc/public_html/lab2/PHPmailer/src/SMTP.php line 327]
2019-02-28 12:00:48 SMTP ERROR: Failed to connect to server: Network is unreachable (101)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Message could not be sent.Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Please follow the link to the troubleshooting guide in the error message which gives details of how to diagnose this exact problem.

@ErfanImmortal

if i disable this line , email will be send
«//$mail->isSMTP(); // Set mailer to use SMTP»

@Synchro

That means you’re not using SMTP. It looks like your ISP blocks you from using outbound SMTP, which is exactly what the guide says. When it says «network is unreachable» , it means it can’t reach your network for sending via SMTP. Bear in mind that while sending may «work», you’re likely to run into problems because you’re forging your from address.

@ErfanImmortal

So i solve my previous problem
but i have new problem
if get this error
Invalid address: (to):
Message could not be sent.Error: You must provide at least one recipient email address.

i have form.html with this code

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title>Send Email</title>
<link rel="stylesheet" type="text/css" href="main.css">	
<script  src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
	<!--[if IE]><script>
	$(document).ready(function() { 
$("#form_wrap").addClass('hide');
})
</script><![endif]-->
</head>
<body>
	<div id="wrap">
		<div id='form_wrap'>
			<form action="submit.php" method="post">
				<p>Send Email</p>
				<label for="email">Email </label>
				<input type="text" name="emailphp" value="" id="emailphp" />	
				<label for="subject">Subject </label>
				<input type="text" name="subjectphp" value="" id="subjectphp" />
				<label for="message">Your Message : </label>
				<textarea  name="messagephp" value="Your Message" id="messagephp" ></textarea>				
				<input type="submit" name ="submit" value="Now, Send!" />
			</form>
		</div>
	</div>
</body>
</html>

and i have «submit.php» too

<?php

// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;

require 'PHPmailer/src/Exception.php';
require 'PHPmailer/src/PHPMailer.php';
require 'PHPmailer/src/SMTP.php';
$mail = new PHPMailer;                              // Passing `true` enables exceptions

if (isset($_POST['submit'])) {
    $emailinp = $_POST['email'];
    $subjectinp = $_POST['subject'];
    $messageinp = $_POST['message'];
}

    //Server settings
	$mail->SMTPDebug = 4; 
	$mail->isSMTP();                                      // Set mailer to use SMTP
	$mail->Host = 'server119.web-hosting.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'admin@marviiii.com';                 // SMTP username
    $mail->Password = '*******';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to
    //Recipients
    $mail->setFrom('admin@marviiii.com', 'Mari');
    $mail->addAddress($emailinp); 
    $mail->addReplyTo('marviiii@gmail.com');
    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = $subjectinp ;

	$mailContent = '
<h2>Eri</h2>
<p>Eri</p>
<p>Eri</p>';

    $mail->Body    = $mailContent ;

if(!$mail->send()){
    echo 'Message could not be sent.';
    echo 'Error: '. $mail->ErrorInfo;
}else{
	echo 'Message has been sent';
}	

?>

@ErfanImmortal

<?php

// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;

require 'PHPmailer/src/Exception.php';
require 'PHPmailer/src/PHPMailer.php';
require 'PHPmailer/src/SMTP.php';
$mail = new PHPMailer;                              // Passing `true` enables exceptions

if (isset($_POST['submit'])) {
    $emailinp = $_POST['email'];
    $subjectinp = $_POST['subject'];
    $messageinp = $_POST['message'];
}

    //Server settings
	$mail->SMTPDebug = 4; 
	$mail->isSMTP();                                      // Set mailer to use SMTP
	$mail->Host = 'server.web-hosting.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'admin@marii.com';                 // SMTP username
    $mail->Password = '********';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to
    //Recipients
    $mail->setFrom('admin@marii.com', 'Mariii');
    $mail->addAddress($emailinp); 
    $mail->addReplyTo('test@gmail.com');
    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = $subjectinp ;

	$mailContent = '
<h2>Eri</h2>
<p>Eri</p>
<p>Eri</p>';

    $mail->Body    = $mailContent ;

if(!$mail->send()){
    echo 'Message could not be sent.';
    echo 'Error: '. $mail->ErrorInfo;
}else{
	echo 'Message has been sent';
}	

?>

@Synchro

You’re only using the submit check to set variables — you’re still trying to send anyway, even if it’s not a submission. You’ve also got no error checking on the addAddress call, in case someone submits an invalid address (it returns false if the address is bad).

@ErfanImmortal

You’re only using the submit check to set variables — you’re still trying to send anyway, even if it’s not a submission. You’ve also got no error checking on the addAddress call, in case someone submits an invalid address (it returns false if the address is bad).

thanks
solved
my next problem is smtp with send grid
how can i send email with sendgrid smtp?

@Synchro

It should be a matter of changing the Host, Username and Password properties — but read their docs.

@ap1437

@Synchro

This may come as a bit of a surprise, but you might want to click that link and read what it says?

@PHPMailer
PHPMailer

locked as resolved and limited conversation to collaborators

May 28, 2021

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,24914 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,24914 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

0 Пользователей и 1 Гость просматривают эту тему.

  • 4 Ответов
  • 8331 Просмотров

SMTP connect() failed https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
такая ошибка возникает при отправке тестового сообщения.
используется SMTP
Send Mail yes
Disable Mass Mail no
from e-mail
from name
mailer SMTP
smtp.yandex.ru
465 port
ssl
SMTP Authentication yes
login
password

из-за чего возникает данная ошибка?
настройки smtp указаны верно и логинпароль так же верные.

пробовал создавать testmail.php
<?php
if (mail(«email@host.ru», «Тема», «Приветnот сервера»))
echo ‘OK’;
else
echo ‘ERROR’;
?>
Выдал ERROR.

Записан

Не можете справиться с задачей сами пишите, решу ее за вас, не бесплатно*.
*Интересная задача, Деньги или Бартер. Натурой не беру!
CodersRank | Контакты | Мой GitHub | Workshop

1. Имеется ввиду стандартная встроенная в Joomla почта для отправки сообщений о регистрации и т.п.
Что тогда лучше использовать для отправки почты?

2. Сервер Joomla крутится на своем сервере Linux

« Последнее редактирование: 25.07.2017, 17:10:25 от Constantin4353 »

Записан

1. Имеется ввиду стандартная встроенная в Joomla почта для отправки сообщений о регистрации и т.п.
Что тогда лучше использовать для отправки почты?

2. Сервер Joomla крутится на своем сервере Linux

попробовал установить почтовик Jmail, получил такую же ошибку. В чем может быть проблема?
Есть предположение, что что-то с настройкой SMTP в файле mail.php… или какие еще могут быть варианты?

проблему решил таким способом:
The workaround is done by adding the SMTPOptions variable to the mail object with particular values to skip the server verification into the file libraries/joomla/mail/mail.php, in the beginning of the function useSmtp().
CODE: SELECT ALL

     // 20160728 workaround for certificate verification failure — ref. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
     $this->SMTPOptions = array(
       ‘ssl’ => array(
         ‘verify_peer’ => false,
         ‘verify_peer_name’ => false,
         ‘allow_self_signed’ => true
       )
     );   
     // 20160728 end

mailboxes-of-different-colors-and-shape-on-pos

Have you encountered an error that says, “PHPMailer SMTP Error: Could not connect to SMTP host?”

Let’s solve it together.

PHPMailer is one of the most popular open source libraries for sending emails with PHP. While it’s easy to deploy and start sending emails, there is a common error which most of us might be facing.

In this document, I have tried sharing the answer for some of the most occurring errors with the PHPMailer:

You may also like: A Complete Guide to Laravel 5.8 Installation.

Depending on your situation, there can be multiple reasons why this error occurs. So, please try to go through the different scenarios below and pick the one that is closest to your use case.

Possible Problem One: Problem With The Latest Version Of PHP

I tried using PHPMailer in many projects in the past, and it worked buttery smooth. But, when I updated the PHP version to 5.6, I started getting an SMTP connection error. Later, I observed that this problem is there with the latest version of the PHP.

I noticed that in the newer version, PHP has implemented stricter SSL behavior, which has caused this problem.

Here is a help doc on PHPMailer wiki that has a section on this issue.

And, here is the quick workaround mentioned in the above wiki, which will help you fix this problem:

$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);

You can also change these settings globally, in the php.ini file but that’s a really bad idea because PHP has done these SSL level strictness for very good reasons only. This solution should work fine with PHPMailer v5.2.10 and higher.

Possible Problem Two: Using Godaddy as the Hosting Provider

If you are running your code on Godaddy and trying to connect to some third-party SMTP provider like smtp.pepipost.com or smtp.sendgrid.com and getting some errors like this:

Mailer Error: SMTP connect() failed.

then nothing there’s really nothing to debug. This occurs because of a wried rule imposed by Godaddy on its user, where Godaddy has explicitly blocked the outgoing SMTP connection to ports 25, 587, and 465 to all external servers except for their own. Godaddy primarily wants their users to use their own SMTP instead of any third party SMTP, which is not at all an acceptable move for the developer community; many have expressed their frustration in form of issues on StackOverflow as well.

Your PHPmailer code might work perfectly fine on a local machine, but the same code, when deployed on Godaddy server, might not work, and that’s all because of this silly rule implemented by Godaddy.

Here are few workarounds to avoid SMTP connection issues in Godaddy:

1. Use Godaddy SMTP Instead of any Third Party:

In case you are sending 1-1 personalized emails, then using Godaddy SMTP makes sense. For that, just make the following changes in your PHPMailer code and you will be done;

$mail->isSMTP();
$mail->Host = 'localhost';
$mail->SMTPAuth = false;
$mail->SMTPAutoTLS = false; 
$mail->Port = 25; 

Note: Godaddy also restricts using any free domains like gmail, yahoo, hotmail, outlook, live, aim, or msn as sender domain/From address. This is mostly because these domains have their own SPF and DKIM policies, and some one can forge the from address if allowed without having custom SPF and DKIM.

But, in case you want to send bulk/emails at scale, then it becomes a bottleneck with high chances of your emails landing in spam. In such a case, I would suggest going with a second option.

2. Use Email APIs Instead Of Any SMTP:

Godaddy can block the outgoing SMTP ports but can’t really block the outgoing HTTP ports (80, 8080). So, I would recommend using some good third party email service provider who provides email APIs to send emails. Most of these providers have code libraries/SDKs like PHPMailer, which you can install and include in your code to start sending emails.

Unlike using Godaddy’s local SMTP, using email APIs will give you better control on your email deliverability.

Possible Problem 3: Getting SMTP Connection Failure on a Shared Hosting Provider

If you are running your code on a shared hosting provider and trying to connect to some third-party SMTP provider like smtp.pepipost.com or smtp.sendgrid.com and getting some errors like this:

SMTP connect() failed.

then, this is mostly because of the firewall rules on their infrastructure that explicitly blocks the outgoing SMTP connection to ports 25, 587, and 465 to all external servers. This rule is primarily to protect the infrastructure from sending spam, but it can also create a really frustrating situation for developers like us.

The only solution to this is the same as I suggested above in the Godaddy section (Use Email APIs instead of any SMTP). Additionally, you could contact the hosting provider to allow connection to SMTP ports.

You might be asking, «How do I check whether your outgoing port (25, 587 or 465) is really blocked or not?»

  1. Trying doing telnet: Using telnet command you can actually test whether the port is opened or not.   If Port 25 is not blocked, you will get a successful 220 response (text may vary).    If Port 25 is blocked, you will get a connection error or no response at all.      
//Type the following command to see if Port 25 is blocked on your network.

telnet pepipost.com 25
  • Trying 202.162.247.93...
    Connected to pepipost.com.
    Escape character is '^]'.
    220 pepipost.com ESMTP Postfix
    Trying 202.162.247.93...
    telnet: connect to address 202.162.247.93: Connection refused
    telnet: Unable to connect to remote host
    1. Use outPorts: outPorts is a very good open source project on GitHub that scans all your ports and gives the result. Once outPorts is installed, you can type the following command in the terminal to check port 25 connectivity:outPorts 25.

Possible Problem 4: SELinux Blocking Issue

In case you are some error like the following:

SMTP -> ERROR: Failed to connect to server: Permission denied (13)

then, most it is most likely that SELinux is preventing PHP or the webserver from sending emails.

This problem occurs often with Linux-based machines like RedHat, Fedora, Centos, etc.

How to debug whether it’s really the SELinux issue which is blocking these SMTP connections?

You can use the getsebool command to check whether the httpd daemon is allowed to make an SMTP connection over the network to send an email.

getsebool httpd_can_sendmail
getsebool httpd_can_network_connect

This command will return a boolean on or off. If it’s disabled, then you will see an output like this;

getsebool: SELinux is disabled

We can turn it on using the following command:

sudo setsebool -P httpd_can_sendmail 1
sudo setsebool -P httpd_can_network_connect 1

If you are running your code on a shared hosting provider and trying to connect to some third-party SMTP provider like smtp.pepipost.com or smtp.sendgrid.com and getting some errors like this.

SMTP connect() failed.

Possible Problem 5: PHPMailer SMTP Connection Failed Because of SSL Support Issue With PHP

There are many popular cases for the failure of SMTP connection in PHPMailer, and the lack of SSL is often a contributing factor.

There might be a case that the Open SSL extension is not enabled in your php.ini, which is creating the connection problem.

So, once you enable the  extension=php_openssl.dll in the ini file, you should enable debug output, so that you can really see that SSL is the actual problem or not. PHPMailer gives a functionality by which you can get detailed logs of the SMTP connection.

You can enable this functionality by including the following code in your script:

$mail->SMTPDebug = 2;

By setting the value of SMTPDebug property to 2, you will be actually getting both server and client level transcripts.

For more details on the other parameter values, please refer the official PHPMailer Wiki.

In case you are using Godaddy hosting, then just enabling SSL might not fix your problem. 

Possible Problem 6: PHPMailer Unable to Connect to SMTP Because ff the IPv6 Blocking Issue

There are some set of newer hosting companies, including DigitalOcean, that provide IPv6 connectivity but explicitly block outgoing SMTP connections over IPv6 but allow the same over IPv4.

You can work around this issue by setting the host property to an IPv4 address using the gethostbyname   function.

$mail->Host = gethostbyname('smtp.pepipost.com');

Note: In this approach, you might face a certificate name check issue but that can be workaround by disabling the check, in SMTPOptions.

This is mostly an extreme case. Most of the time, it’s the port block issue by the provider, like DigitalOcean in this case.

So, it is important to first get confirmed whether the port is really unlocked or not before digging further into the solution.

Possible Problem 7: Getting the Error “Could Not Instantiate Mail Function”

This issue happens primarily when your PHP installation is not configured correctly to call the mail()   function. In this case, it is important to check the sendmail_path in your php.ini file. Ideally, your sendmail_path should point to the sendmail binary (usually the default path is  /usr/sbin/sendmail).

Note: In case of Ubuntu/Debian OS, you might be having multiple .ini files (under the path  /etc/php5/mods-available), so please ensure that you are making the changes at all the appropriate places.

If this configuration problem is not the case, then try further debugging and check whether you have a local mail server installed and configured properly or not. You can install any good mail server like Postfix.

Note: In case all of the above things are properly in place and you’re still getting this error of “Could not instantiate mail function”, then try to see if you are getting more details of the error. If you see some message like “More than one from person” in the error message then it means that in php.ini the sendmail_path property already contains a from -f parameter and your code is also trying to add a second envelope from, which is actually not allowed.

What Is the Use of IsSMTP()?

 isSMTP() is used when you want to tell the PHPMailer class to use the custom SMTP configuration defined instead of the local mail server.

Here is a code snippet of how it looks like;

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@example.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  = "This is a Test Message";
           $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.';
           }

Many times, developers get the following error:

 “SMTP -> ERROR: Failed to connect to server: Connection timed out (110). SMTP
 Connect() failed. Message was not sent. Mailer error: SMTP Connect() failed.”
 

If you’re constantly getting the above error message, then just try identifying the problem as stated in the above sections.

If you like this tutorial, do like and share, and feel free to comment if you have any questions. 

Related Articles

  • Develop a REST API in PHP.
  • How to Create a Simple and Efficient PHP Cache.

Opinions expressed by DZone contributors are their own.

SMTP connect() failed is a common error in WordPress. If you get the error and hope to know how to solve it, then don’t hesitate to explore the blog today!

Why does the SMTP connect() failed error appear?

Normally, the error SMTP connect() failed turns out because the user misconfigured the SMTP mail sending method (Google Mail Service). Besides that, you know that PHPMailer is the default mailer in WordPress. In case there is something wrong that disallows the PHPMailer to contact the SMTP server, you can also get the error. Further, many other reasons and factors can also cause this error. In order to fix this issue, let’s take a look at the following methods.

How to fix the SMTP connect() failed error

If you desire to address the error SMTP connect() failed in an exact and effective way, it’s a good idea for you to identify the reason first, and then fix it. So, let’s check each possibility now!

SMTP host and port settings

  • in the SMTP Host section, fill out your mail server’s name first and ensure that the DNS for the SMTP host is correct.
  • The default SMTP port is 25. For mail servers, we will use custom ports 587 for SMTP in order to avoid spam.
  • In some cases, the mail servers use firewall rules to restrict access to port 25. If you are in the case, it’s necessary for you to offer your IP white-listed to avoid the error.
  • Now, let’s confirm that the connection of the SMTP server and port is good by using the command:
    telnet domain.com 25
  • After ensuring that the SMTP connection is ok, let’s use the suitable hostname and port number. If the connection is not ok, you will get the error SMTP connect() failed.

SMTP authentication details

As you know, each mail server has an authentication system with the purpose of validating the users before it allows them to connect to it and then send emails. Let’s make sure that the authentication details given are right, if not, WordPress can’t send emails and you may get the error SMTP connect() failed.

SMTP encryption settings

You should select SMTP with encryption if you need the email transmission secure. You can do that by choosing the option ‘Use SSL Encryption’ in the WordPress setting. However, in some email servers, you haven’t turned on SSL/TLS support yet. That means the mail can not get delivered and the error will happen.

Therefore, it’s a good suggestion for you to ensure that you configure the OpenSSL utility correctly in the mail server. Besides that, don’t forget to verify the SSL certificate with the command below:

openssl s_client -starttls smtp -crlf -connect mail.domain.com:25

If you are utilizing expired or self-signed certificates, this may cause the error SMTP connect() failed. Therefore, you can solve this issue by configuring SSL for the mail server or changing the SMTP from encryption to no encryption.

Support for 3rd party apps

Since Gmail servers have many security restrictions, they may block certain mail client apps. If you are in this case, it’s necessary for you to loosen the security. In order to do that, you need to access your Gmail, then open My Account -> Lestt Secure Apps -> Turn on Access for less secure apps.

WordPress SMTP plugins

Sometimes, the error SMTP connect() failed may appear because of the conflict with the SMTP plugin you are using. If this is the reason, you just need to stop using it and find alternative plugins. Here are some recommended WordPress SMTP Plugins for you to try.

Final Words

In conclusion, we are happy to offer you some solutions for the error SMTP connect() failed. If you think the blog is helpful, then don’t hesitate to share it with other users. Besides, don’t forget to leave your comment below if you have trouble related to this topic.

Furthermore, let’s have a look at our well-designed and easy-to-use free WordPress themes here. Thanks for your visit and have a great day!

  • Author
  • Recent Posts

Lt Digital Team (Content &Amp; Marketing)

Welcome to LT Digital Team, we’re small team with 5 digital content marketers. We make daily blogs for Joomla! and WordPress CMS, support customers and everyone who has issues with these CMSs and solve any issues with blog instruction posts, trusted by over 1.5 million readers worldwide.

Lt Digital Team (Content &Amp; Marketing)

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

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

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

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Php7ts dll ошибка при проверке php
  • Pioneer flac ошибка 19