29

I am new to PHP. I was trying to send myself a sample e-mail through PHPmailer. I am using gmail's smtp server. I am trying to send a sample mail from my gmail account to my yahoo account. But I am getting the error : Mailer Error: SMTP connect() failed.
Here is the code :

<?php

require "class.phpmailer.php";
$mail = new PHPMailer(); 
$mail->IsSMTP();                              // send via SMTP
$mail->Host = "ssl://smtp.gmail.com";
$mail->SMTPAuth = true;                       // turn on SMTP authentication
$mail->Username = "[email protected]";        // SMTP username
$mail->Password = "mypassword";               // SMTP password
$webmaster_email = "[email protected]";       //Reply to this email ID
$email="[email protected]";                // Recipients email ID
$name="My Name";                              // Recipient's name
$mail->From = $webmaster_email;
$mail->Port = 465;
$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";
}
?>

I am using WAMP server on a Windows 7 64-bit machine. What could be the prob?
Please help me solve this. Thanks!

6
  • Just to let you know, require is a language construct and () aren't neccessary.
    – Ryan
    Apr 8, 2014 at 4:36
  • @RPM Thanks! I changed it. But, Please help me solve this problem Apr 8, 2014 at 4:37
  • I think you missed server details details
    – Riskhan
    Apr 8, 2014 at 4:38
  • @Krishna Please tell me what details I should add. Apr 8, 2014 at 4:40
  • Where is host parameter in your code ?
    – Riskhan
    Apr 8, 2014 at 4:46

18 Answers 18

29

The solution of this problem is really very simple. actually Google start using a new authorization mechanism for its User.. you might have seen another line in debug console prompting you to log into your account using any browser.! this is because of new XOAUTH2 authentication mechanism which google start using since 2014. remember.. do not use the ssl over port 465, instead go for tls over 587. this is just because of XOAUTH2 authentication mechanism. if you use ssl over 465, your request will be bounced back.

what you really need to do is .. log into your google account and open up following address https://www.google.com/settings/security/lesssecureapps and check turn on . you have to do this for letting you to connect with the google SMTP because according to new authentication mechanism google bounce back all the requests from all those applications which does not follow any standard encryption technique.. after checking turn on.. you are good to go.. here is the code which worked fine for me..

require_once 'C:\xampp\htdocs\email\vendor\autoload.php';

define ('GUSER','[email protected]');
define ('GPWD','your password');


// make a separate file and include this file in that. call this function in that file.

function smtpmailer($to, $from, $from_name, $subject, $body) { 
    global $error;
    $mail = new PHPMailer();  // create a new object
    $mail->IsSMTP(); // enable SMTP
    $mail->SMTPDebug = 2;  // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPAuth = true;  // authentication enabled
    $mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
    $mail->SMTPAutoTLS = false;
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 587;

    $mail->Username = GUSER;  
    $mail->Password = GPWD;           
    $mail->SetFrom($from, $from_name);
    $mail->Subject = $subject;
    $mail->Body = $body;
    $mail->AddAddress($to);
    if(!$mail->Send()) {
        $error = 'Mail error: '.$mail->ErrorInfo; 
        return false;
    } else {
        $error = 'Message sent!';
        return true;
    }
}
4
  • 2
    Thanks a lot. +100 for your answer. I had gone through all the gmail settings and spend my whole day but only start working once i turn off less secure apps option Nov 22, 2016 at 1:32
  • 1
    appologies turn on and one more thing i have used 465 with ssl and i have't face any bounce back from gmail. Nov 22, 2016 at 1:39
  • 1
    I love you "do not use the ssl over port 465, instead go for tls over 587". I lost so many hours.... May 24, 2017 at 3:45
  • Thanks after hours of looking found your contribution here May 7, 2020 at 21:04
18

You need to add the Host parameter

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

Also, check if you have open_ssl enabled.

<?php
echo !extension_loaded('openssl')?"Not Available":"Available";
7
  • I added the parameter but it shows the same error Mailer Error: SMTP connect() failed.. Apr 8, 2014 at 4:39
  • 1
    Is machine connected to Internet ?
    – Riskhan
    Apr 8, 2014 at 4:40
  • @Krishna Yes my PC is connected to the Internet Apr 8, 2014 at 4:42
  • 1
    Well, that's why it didn't work , Open your php.ini and search for this line ;extension=php_openssl.dll and remove the semi colon before it , save the file and restart your webserver. You will see your coding working after you do this change. Apr 8, 2014 at 4:47
  • 1
    I just wanted to thank @ShankarDamodaran for your answer. It saved me! Thanks Jun 30, 2021 at 19:04
17

Solved an almost identical problem, by adding these lines to the standard PHPMailer configuration. Works like a charm.

$mail->SMTPKeepAlive = true;   
$mail->Mailer = “smtp”; // don't change the quotes!

Came across this code (from Simon Chen) while researching a solution here, https://webolio.wordpress.com/2008/03/02/phpmailer-and-smtp-on-1and1-shared-hosting/#comment-89

4
  • looks like this command solved the issue; mainly only the second command was necessary. It is interesting that my gmail account is filtering as spam the received email.
    – Radu Linu
    Jun 16, 2018 at 12:11
  • This should be okay. But it's not a proper solution. Received emails are tagged as spam. Better use a PHP framework to send emails with SMTP. Sep 25, 2019 at 8:08
  • 4
    DON'T do this, this makes it NOT work with SMTP at all, its just sent by your host that's why you get the illusion that its working Nov 13, 2019 at 19:55
  • Thanks! this did the trick. $mail->Mailer = “smtp”; May 10, 2022 at 8:38
7

Troubleshooting

You have add this code:

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

And Enabling Allow less secure apps: "will usually solve the problem for PHPMailer, and it does not really make your app significantly less secure. Reportedly, changing this setting may take an hour or more to take effect, so don't expect an immediate fix"

This work for me!

4
$mail->SMTPKeepAlive = true;   
$mail->isSendMail(); // instead of  isSMTP();

On shared hosting, your mail server may occasionally experience connection issues. Here I found solution

[Edit]

Here is the link content, in case the link stop working for some reason (it happens)

PHPMailer and SMTP on 1and1 shared hosting

I use PHPMailer on my 1and1 shared hosting account. Recently, I could not send email anymore.

I tried debugging and this is the error that PHPMailer throws:

Language string failed to load: connect_host

After googling for a solution and trying different SMTP servers, accounts and SMTP ports, I decided to switch to sendmail and it worked like a charm! All I needed to do was to replace $mail->isSmtp() with:

$mail->isSendMail()

sendMail is located in its default location on 1and1 servers : /usr/sbin/sendmail, so no change of settings was required.

Conclusion:

1and1 probably closed its outgoing SMTP ports on its shared hosting servers. Consequently, if you use PHPMailer, don’t use SMTP mode anymore.

0
3

Just make sure you passed the right parameters eg. the correct outgoing server host, username, and password

$mail->SMTPDebug = false;
$mail->Host = 'email_smtp_host'
$mail->SMTPAuth = false
$mail->Username = 'username'
$mail->Password = 'password'
$mail->SMTPSecure 'tls'
$mail->Port = '587'
2

If anyone is still unable to solve the issue, please check following thread and follow callmebob's answer.

PHPMailer - SMTP ERROR: Password command failed when send mail from my server

2

I fixed it ...

https://github.com/PHPMailer/PHPMailer/tree/5.2-stable

<?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$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 = '[email protected]';                 // SMTP username
$mail->Password = 'pass';                           // SMTP password
//$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 25;                                    // TCP port to connect to

$mail->setFrom('[email protected]', 'Mailer');
$mail->addAddress('[email protected]', 'User');     // Add a recipient

$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';
}

Turn on access and enjoy..! That is on Gmail account setting.

Turn On access

1

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 = "[email protected]";       //Reply to this email ID
$email="[email protected]";                // 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']          = '[email protected]';
$email['pass']          = 'from password';
$email['from']          = 'From Name';
$email['reply']         = '[email protected]';
$email['replyname']     = 'Reply To Name';

$addresses_to_mail_to = '[email protected];[email protected]';
$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;
}
5
  • I didn't understand your answer. I am trying to send an e-mail from my gmail account TO my yahoo account not vice-versa. Correct me if I'm wrong but I should give the username and password of my gmail account and not my yahoo account. Apr 8, 2014 at 4:44
  • Correct, you would put in your GMail account credentials. Give me a moment, and I will update the function so you can use that :) Apr 8, 2014 at 4:47
  • Thanks Sanuel. I got it working now. +1 for helping me. I am interested in the function. Please update it. Apr 8, 2014 at 4:52
  • 1
    Function has been updated. It allows for attaching files as well, but you must attach using the full path. $attach can be set to one value (aka $attach = '/home/somefile.txt') or it can be an array of files ( $attach = Array( '/home/somefile1.txt', '/home/somefile2.txt' ) ). Apr 8, 2014 at 4:58
  • 1
    The only quirk I had, is for some reason, if i add a parameter to the function (aka, $ssl), I can not use that value as the value for $mail->SMTPSecure (aka, $ssl = "tls"; then $mail->SMTPSecure = $ssl doesn't work... so if you need to switch, just set that line directly. Apr 8, 2014 at 5:00
1

if everything fails then for gmail you must turn on access to 3rd party apps to connect to ur gmail account.

https://www.google.com/settings/security/lesssecureapps // turn it on

0

If you're using VPS and with httpd service, please check if your httpd_can_sendmail is on.

getsebool -a | grep mail

to set on

setsebool -P httpd_can_sendmail on
0

Try adding this line to your script. This worked for me!

$mail->Mailer = “smtp”;

1
  • DON'T do this, this makes it NOT work with SMTP at all, its just sent by your host that's why you get the illusion that its working Nov 13, 2019 at 19:55
0

This is usually a result of the server not accepting SSLv2 or SSLv3 connections which is a standard for cPanel/WHM in favor of TLS only connections. You can check this by going to WHM>>Service Configuration>>Exim Configuration Manager -> Options for OpenSSL

0
 $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );
1
  • Please explain why/how this solves the problem. See How To Answer
    – jasie
    Sep 16, 2020 at 12:09
0
<?php

use PHPMailer\PHPMailer\PHPMailer;

require_once "PHPMailer/src/Exception.php";
require_once "PHPMailer/src/PHPMailer.php";
require_once "PHPMailer/src/SMTP.php";



$mail = new PHPMailer();

$mail ->isSMTP();
$mail ->Host ="smtp.gmail.com";
$mail -> SMTPAuth = true;
$mail ->Username = '[email protected]';
$mail ->Password = 'password';
//$mail ->SMTPSecure=PHPMailer::ENCRYPTION_STARTTLS;
$mail ->Port = '587';
$mail ->SMTPSecure ='tls';
$mail ->isHTML(true);

$mail ->setFrom('[email protected]','email send name');

$mail ->addAddress('[email protected]');
$mail ->Subject = 'HelloWorld';
$mail ->Body = 'a test email';


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



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

?>

make sure that you configure less secure app settings in gmail using this link https://www.google.com/settings/security/lesssecureapps and make sure you downloaded PHPMailer-master.zip from github

working fine with MAMP server locally :)

0

After days of searching, I found out that the protocol name needs to be in lowercase.

$mail->SMTPSecure = "ssl"; # lowercase
0

find the "class.smtp.php" file original:

$this->smtp_conn =fsockopen(
$host,
$port,
$errno,
$errstr,
$timeout
);

change to:

$this->smtp_conn = @stream_socket_client(
$host,
$port,
$errno,
$errstr,
$timeout
);
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Feb 2, 2022 at 8:20
0

Check whether the virus guard blocks the mail. If it is turn off and try again.

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Aug 4, 2023 at 13:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.