Ошибка smtp connect failed phpmailer

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

hi, i’m new to php and i have been trying to send e-mail through php, phpmailer is the only class i find most recommended by most of the developers. i tried almost all solutions for my error. i cant find the fix. I have tried the link below, but didn’t get what to do, and googled for the solution, couldn’t find any, which works for me. tried almost all solutions, but it keeps showing me the same error.

Message could not be sent.Mailer Error:SMTP connect() failed.https://github.com/PHPMailer/PHPMailer/wiki/TroubleshootingAvailable

tried the above link, as im new to php, im stuck.

fr all smtpdebug: 1,2,3,4, its giving same error… but php mail() function is working fine.

and our hosting provider says this…

We have the following list of ports open on our shared hosting plans:

HTTP/HTTPS — 80/443
GMail — 465/587/995/993
TOMCAT — 8080
SMTP/IMAP/POP — 25/143/110

here is the code im using. please help me to resolve the error. thanx in advance.

<?php


require 'phpmailer/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 = 'userid@gmail.com';                 // SMTP username
$mail->Password = 'secret';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                                    // TCP port to connect to

$mail->From = userid@gmail.com';
$mail->FromName = 'Mailer';
//$mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
$mail->addAddress('name@mysite.com');               // Name is optional

//$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$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';
}
?>

Выдает Ошибка: SMTP connect() failed.

<?php 

$name = $_POST['user_name'];
$phone = $_POST['user_phone'];

require_once('phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer;
$mail->CharSet = 'utf-8';

//$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 = 'danil.plotnikov111@gmail.com';                 // Наш логин
$mail->Password = 'danil27082001';                           // Наш пароль от ящика
$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;                                    // TCP port to connect to
 
$mail->setFrom('danil.plotnikov111@gmail.com', 'danil');   // От кого письмо 
$mail->addAddress('danil.plotnikov111@gmail.com');     // Add a recipient
//$mail->addAddress('ellen@example.com');               // Name is optional
//$mail->addReplyTo('info@example.com', 'Information');
//$mail->addCC('cc@example.com');
//$mail->addBCC('bcc@example.com');
//$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Новая заявка';
$mail->Body    = '
	Пользователь оставил свои данные <br> 
	Имя: ' . $name . ' <br>
	Телефон: ' . $phone . '';

$mail->AltBody = 'Это альтернативный текст';

if(!$mail->send()) {
    echo "error";
    echo 'Ошибка: ' . $mail->ErrorInfo;
} else {
    echo "success";;
}

?>

В гугл разрешил отправку с неизвестных источников

WordPress is the most by and large used CMS for locations. Passing on sends from WordPress is required in circumstances. PHPMailer SMTP Connect () Faile for instance. Contact structure passages or mystery express resets. PHPMailer SMTP Connect () Failed. Is a by and large experienced screw-up in WordPress. Due to which messages disregard to be sent from your WordPress site.

Composing email settings in WordPress

As per normal procedure, WordPress uses the PHP Mail ability to send messages. However “PHPMailer SMTP Connect () Failed”. Using PHP mail work is a less secured method and makes the server frail against spamming. Along these lines various web servers have PHP mail () turn out weakened for security purposes. In those servers “PHPMailer SMTP Connect () Failed”. Sends can be sent from WordPress using SMTP.

SMTP uses suitable approval

SMTP uses suitable approval and is thusly more secure. There are WordPress modules, for instance ‘WP Mail SMTP’, that should be organized to send sends through SMTP. At the point when the SMTP module is ordered. PHPMailer SMTP Connect () Failed. A new ‘Email’ menu will show up under the Settings in WP.

You can organize the email transport settings in that decision. You can give me your email address. Secret key mail server name. Port in the Email settings and save it. You can test the mail transport to check whether the settings are fine.

The going with settings can be planned in the Email settings:

  • From Email - the email address you wanted to send messages from.
  • From Name - the name that your messages will be gotten from.
  • Mailer - you can pick between the default PHP Mail limit and SMTP.
  • SMTP Host - the hostname for your SMTP server.
  • SMTP Port - the port for your mail server ordinarily 25.
  • Encryption - accepting you wanted to engage SSL/TLS encryption for the mail server.
  • Approval - really check out it for mail server affirmation.
  • Username - the username for your SMTP server.
  • Secret word - the mysterious expression for your SMTP server.

What causes the error ‘SMTP partner () failed’ in WordPress

The default mailer is PHPMailer in WordPress and numerous objections use it to send sends. Be that as it may “PHPMailer SMTP Connect () Failed”. Can give an ‘SMTP interface () failed’ error on the off chance that PHPMailer can’t contact the SMTP server.

Also, if the settings for the SMTP server aren’t masterminded precisely. “PHPMailer SMTP Connect () Failed”. It will not send sends viably from the server and give an ‘SMTP partner () failed’ error.

The bungle ‘SMTP interface () failed’ can be caused due to many reasons.

which we’ll look at separately:

  • Wrong username and mystery state is given in SMTP approval.
  • SMTP port discouraged in mail server firewalls.
  • SSL/TLS does not help in the mail server and encryption is engaged in the WP setting.
  • Security restrictions by pariah servers for instance. Gmail or email applications.
  • Increases to WordPress module or PHPMailer versions. That have further developed security components or bugs.


People Also Ask

Question # 1: How do you fix SMTP connect () failed?

Answer: How to fix SMTP Error Failed to connect to the server

  1. Modify the firewall rules on the server to allow outbound connections on ports like 465.
  2. Modify the SMTP restrictions on the server.
  3. Edit PHPMailer settings like Host Port etc.
  4. Correct DNS resolution for the mail server.

Question # 2: Could not be sent mailer error SMTP connect () failed?

Answer: Mailer Error: SMTP connect() failed. then nothing there’s 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.

Question # 3: Can’t connect to SMTP port?

Answer: If the mail server has another service running on the SMTP port configured, the same issue occurs. Another issue related to the mail server is the lack of support for encryption. If the OpenSSL module is not configured properly or if the PHP extension is not working fine. It will throw errors during SMTP connections.

Question # 4: What is an SMTP server error?

Answer: An SMTP response code is a three-digit code that the servers use to communicate throughout the email sending process. If there is a communication error. You will receive an SMTP error code a message that indicates the specific problem. Like the end of server communication which is error code 550 (The request failed).

Question # 5: Can’t connect to port 587?

Answer: If the SMTP port 587 is not blocked, the 220 response will appear. This message may vary from system to system. If an Unable to connect or Connection refused message appears. That means the port is blocked. In this case. We recommend you disable the firewall or contact your ISP.

Learn More About

Question # 6: Can’t connect to Java SMTP host error?

Answer: MailConnectException Couldn’t connect to host port. There can be multiple reasons for this but the most common reason for this error is the port. That you are using to send SMTP mails. Few ISPs/hosting providers block SMTP outgoing port 25. If that is the case try changing the port to 587 or 2525.

Question # 7: How do I use PHPMailer in WordPress?

Answer: To configure PHPMailer in WordPress. There is a hook available which is phpmailer init. Using phpmailer_init hook. We can access the PHPMailer object and set the arguments to it. Open your active theme’s functions. PHP file and place the below code at the end of a file.

Question # 8: What is an SMTP server name?

Answer: An SMTP email server will have an address (or addresses) that can be set by the mail client or application. That you are using and is generally formatted as smtp.serveraddress.com. For example, Gmail’s SMTP server host address is smtp.gmail.com. Twilio SendGrid’s is smtp.sendgrid.com.

Question # 9: Can’t connect to SMTP host 111 Connection Refused?

Answer: Some of them are getting the error SMTP ERROR. Failed to connect to server: Connection refused (111) error. To fix this error you would need to disable SMTP Restrictions, from your server. This feature prevents users from bypassing the mail server to send mail. A common practice used by spammers.

Question # 10: What is the common problem that occurs when using an SMTP mailing list?

Answer: If you use port 25 for SMTP it might be blocked. It is common for mail services and ISPs to block them. The problem could also be another firewall.  Is installed locally on the sender’s workstation and blocks SMTP connections. Outlook could also just be set up incorrectly.



Guidelines to fix screw up “SMTP interface () failed” in WordPress

To fix the slip-up, “PHPMailer SMTP Connect () Failed”. The first thing is to do is to recognize the justification behind the error. By checking out and dealing with each possibility.

1. SMTP host and port settings

Enter the name of your mail server in the SMTP Host region. This is regularly the region name or ‘mail.domain.com’. Guarantee that the DNS for SMTP has to settle precisely. Give the port number as 25, the default SMTP port. For mail servers that use custom ports. PHPMailer SMTP Connect () Failed” for instance. 587 for SMTP to keep away from spamming, give that port.

It is moreover possible that particular mail servers limit the permission to their port 25 using firewall rules. In such cases. PHPMailer SMTP Connect () Failed”.

  • Your IP should be white-recorded in the firewall to avoid SMTP errors.

To attest that the accessibility to the SMTP server and port is ended up extraordinary.

Use the request:

  • telnet domain.com 25

Use the fitting hostname and port number. In the wake of attesting that the SMTP connection is ended up extraordinary. On the off chance that the organization fails to develop. “PHPMailer SMTP Connect () Failed”. Mail movement will crash and burn with the bumble SMTP interface () failed.

2. SMTP confirmation nuances

Each mail server has a confirmation structure to support the customers before allowing them to interface with it and send sends. In your WordPress Email settings. “PHPMailer SMTP Connect () Failed”, enter these nuances.

“PHPMailer SMTP Connect () Failed”. Give the email account username and secret word. Enter the full ‘user@domain.com’ as the username if there has to be an event of non-default accounts. Whenever the email account secret expression is changed or invigorated for security reasons.

Make sure to change the mysterious key in ‘Email settings’ also. In case the check nuances given aren’t right. WordPress will disregard sending sends and give the misstep “PHPMailer SMTP Connect () Failed”.

3. SMTP encryption settings

For secure email transmission, it is reliably judicious to pick SMTP with encryption. This has to be conceivable using the Use SSL encryption decision in the WordPress setting. However, in some email servers. This SSL/TLS sponsorship may not be enabled. In those cases, “PHPMailer SMTP Connect () Failed”. On the off chance that you pick encryption. Sends may not get passed on. Guarantee that the OpenSSL utility is planned fittingly in your email server. Moreover, take a look at the SSL validation for your mail server, using the request:

  • openssl client - starttls smtp - crlf - partner mail.domain.com:25

Using passed or self-stamped verifications can cause the mail transport using SSL to fail and give the error ‘SMTP interface () failed’. So the plan in those cases is to plan SSL for your mail server suitably or change the SMTP encryption to ‘No Encryption’. “PHPMailer SMTP Connect () Failed”. Which is a less secure one.

4. Support for outcast applications

Gmail servers have a huge load of security impediments set up. “PHPMailer SMTP Connect () Failed”. Which may make them block tries from explicit mail client applications. In those cases. You should deliver the wellbeing endeavors. In Gmail. Go to ‘My Account’ – > ‘Less Secure Apps’ fragment. Turn on the decision. Access for less secure applications. If you are using Gmail as your mail server. A better decision is to present and activate the ‘Gmail SMTP’ module for WordPress.

5. WordPress SMTP modules

At long last, the SMTP module-related issues can in like manner cause ‘SMTP interface failed’ error. In those cases. “PHPMailer SMTP Connect () Failed”. You have to stop using the WP Mail SMTP module and pick various ones. Some WordPress SMTP modules that can be used are Postman – SMTP Mailer – Mailgun, etc. For sending sends from WordPress objections.

Termination

Various varieties for SMTP interface () failed goof. Mail () without being related or SMTP Error  Could not connect with SMTP have. Regardless of the plan settings we’ve discussed. “PHPMailer SMTP Connect () Failed”. One critical feature recollect is the security protections to take during WordPress or PHPMailer upgrades.

Around here at ARZHOST. Our elaborate inclusion in both WordPress customization and server association has helped us with performing upgrades. Fixes in locations without making any business get-away. On the off chance that you’d like to acknowledge. How to get and manage your servers and adjust your locations to hinder errors. PHPMailer SMTP Connect () Failed. We’d be happy to banter with you.

Answer by Kaitlyn Goodwin

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

Still not working.. The error generated is this » ERROR: Failed to connect to server: Connection timed out (110)SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed.»

– Muli

Sep 3 ’13 at 9:27

,

Meta Stack Overflow

,

Stack Overflow
Public questions & answers

Remove or comment out the line-

$mail->IsSMTP();

Answer by Haley Quinn

The answer from @jvitoroc helped me.
Changed from $mail->Host = ‘smtp.gmail.com’; to $mail->Host = ‘tls://smtp.gmail.com:587’ and removed $mail->Port= 587;,require ‘PHPMailer/PHPMailerAutoload.php’;
require ‘PHPMailer/class.phpmailer.php’;
function Sendmail($to, $subject, $message, $filename, $path){,Maybe I didn’t have the SMTPSecure parameter. I don’t have access to the code, it was from an intern that I was helping. But thanks for the reply,I solved the problem using: $mail->Host = ‘tls://smtp.gmail.com:587’;

<?php

// Mudar Aqui

$email_envio = '[email protected]'; // E-mail receptor
$email_pass = 'password'; // Senha do e-mail

$site_name = 'asdsds'; // Nome do Site
$site_url = 'sdsdsds'; // URL do Site

$host_smtp = 'smtp.gmail.com'; // HOST SMTP Ex: smtp.domain.com.br
$host_port = '465'; // Porta do Host

// Variáveis do Formulário
// Conteúdo do Formulário

// Não mudar a partir daqui

require ('../PHPMailer/PHPMailerAutoload.php');

$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';

$mail->isSMTP();
$mail->Host = $host_smtp;
$mail->SMTPAuth = true;
$mail->Username = $email_envio;
$mail->Password = $email_pass;
$mail->Port = $host_port; 

$mail->From = "[email protected]";

$mail->addAddress("[email protected]");

$mail->FromName = 'Formulário de Contato';
$mail->AddReplyTo("[email protected]", 'joao');

$mail->WordWrap = 70;

$mail->Subject = 'Formulário sd';

$mail->Body = "[email protected]";

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

Answer by Juliette Hendricks

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).,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.,There might be a case that the Open SSL extension is not enabled in your php.ini, which is creating the connection problem., isSMTP() is used when you want to tell the PHPMailer class to use the custom SMTP configuration defined instead of the local mail server.

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

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.

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; 

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

In case you are some error like the following:

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

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

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.

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

$mail->SMTPDebug = 2;

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');

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 = "[email protected]"; // SMTP username
           $mail->Password = "mypasswword"; // SMTP password
           $Mail->Priority = 1;
           $mail->AddAddress("[email protected]","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.';
           }

Answer by Maximus Jacobs

Mailer Error SMTP connect() failed ,I need help i keep getting this error,
Message could not be sent.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting,Your code is correct except few things. I edited your code and the message get sent. Also check whether your username and password is correct or not as I tried with my username and password.And also check did you include the class.phpmailer.php.

Here’s my code

<?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 = 'password';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                                    // TCP port to connect to

$mail->setFrom('[email protected]', 'Mailer');
$mail->addAddress('[email protected]', 'Joe User');     // Add a recipient
//$mail->addAddress('[email protected]');               // Name is optional
//$mail->addReplyTo('[email protected]', 'Information');
//$mail->addCC('[email protected]');
//$mail->addBCC('[email protected]');

//$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$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';
}
?>

Answer by Reese Harvey

Message could not be sent.,so when run code it shows error like this, Save my name, email, and website in this browser for the next time I comment.,$mail->isSMTP(); from code and try again! or also check your username and password in code.

html form:

<form method="post" action="email.php">
  Email: <input name="email" id="email" type="text" /><br />

  Message:<br />
  <textarea name="message" id="message" rows="15" cols="40"></textarea><br />

  <input type="submit" value="Submit" />
</form>

email.php:

<?php

// $email and $message are the data that is being
// posted to this page from our html contact form
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;

require_once('class.phpmailer.php');
require 'PHPMailerAutoload.php';
require 'class.smtp.php';

$mail = new PHPMailer();
$body='hellooooo';
$mail->IsSMTP();

$mail->Host = "ssl://smtp.gmail.com"; // specify main and backup server

$mail->SMTPAuth = true; // turn on SMTP authentication

$mail->Username = "[email protected]"; // SMTP username
$mail->Password = "zzz"; // SMTP password
$mailer->SMTPSecure = 'ssl';
$mailer->Port = 465;//587;
$mail->AddAddress("xxx", "xx");
$mail->SetFrom('[email protected]','xxxx');
$mail->WordWrap = 50;

$mail->IsHTML(true);

$mail->Subject = "You have received feedback from your website!";

$mail->MsgHTML($body);

if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}

echo "Message has been sent";
?>

And removed semicolon in this line ;extension=php_openssl.dll from the following files, and restart the xampp.

c/xampp/apache/bin/php.ini and c/xampp/php/php.ini

It looks like your credentials for connecting to your authentication has failed. found it that it’s a LOT easier to use another SMTP than Gmail, like mandrillapp, free until 12,000 mails.

<?php 

require 'PHPMailer-master/PHPMailerAutoload.php';

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

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp.mandrillapp.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '[email protected]';                 // SMTP username
$mail->Password = 'mandrilapp_will_give_you_a_password';                           // SMTP password
$mail->Port = 587;                                    // TCP port to connect to

$mail->From = '[email protected]';
$mail->FromName = 'Test phpmailer';
$mail->addAddress('[email protected]');               // 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';
}

Answer by Jagger Salgado

This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.

Accept
Learn more…

                $mail = new PHPMailer;
                $mail->isSMTP();
                $mail->Host = "mail.xxxx.co.uk";
                $mail->SMTPAuth = true;
                $mail->Username = "[email protected]o.uk";
                $mail->Password = "xxxx";
                $mail->SMTPSecure = 'tls';
                $mail->Port = "587";
                $mail->setFrom('[email protected]', 'xxxx');
                $mail->addAddress($emailAddress, $firstName . " " . $lastName);
                $mail->isHTML(true);
                $mail->Subject = 'Forgot Password';
                $mail->Body = $emailBody;

if($mail->send()) :
//success message
else :
//error message inc $mail->ErrorInfo.
endif;

Понравилась статья? Поделить с друзьями:
  • Ошибка smart жесткого диска вылечить
  • Ошибка slrr create undefined gametype constructor
  • Ошибка smart жесткого диска ssd
  • Ошибка slow down на мицубиси лансер 10
  • Ошибка smart жесткого диска mac os