SMTP connection error when sending email using Phpmailer

Asked

Viewed 34,147 times

3

I’m trying to implement email sending with the library Phpmailer, but brought me the following mistakes:

Edit: I’m testing it locally.

SMTP -> ERROR: Failed to connect to server: Uma tentativa de conexão falhou porque o componente conectado não respondeu corretamente após um período de tempo ou a conexão estabelecida falhou porque o host conectado não respondeu. (10060)
SMTP Error: Could not connect to SMTP host.

Edit 2: Follows part of var_dump() of the object with error related messages

 private 'language' => 
    array (size=13)
      'provide_address' => string 'You must provide at least one recipient email address.' (length=54)
      'mailer_not_supported' => string ' mailer is not supported.' (length=25)
      'execute' => string 'Could not execute: ' (length=19)
      'instantiate' => string 'Could not instantiate mail function.' (length=36)
      'authenticate' => string 'SMTP Error: Could not authenticate.' (length=35)
      'from_failed' => string 'The following From address failed: ' (length=35)
      'recipients_failed' => string 'SMTP Error: The following recipients failed: ' (length=45)
      'data_not_accepted' => string 'SMTP Error: Data not accepted.' (length=30)
      'connect_host' => string 'SMTP Error: Could not connect to SMTP host.' (length=43)
      'file_access' => string 'Could not access file: ' (length=23)
      'file_open' => string 'File Error: Could not open file: ' (length=33)
      'encoding' => string 'Unknown encoding: ' (length=18)
      'signing' => string 'Signing Error: ' (length=15)

Below follows my shipping code:

$email = new PHPMailer();

$email->IsSMTP();
$email->SMTPSecure = "ssl"; // tbm já tentei tls
$email->Port = 587; // tbm já tentei 465 e tbm sem porta nenhuma
$email->SMTPDebug = 1;
$email->Host = "smtp.gmail.com";    
$email->SMTPAuth = true;
$email->Username = "[email protected]";
$email->Password = "minhaSenha";
$email->From = $para;

$email->SetLanguage("en", "../biblioteca/phpmailer/language/");
$email->CharSet = "UTF-8";
$email->FromName = $nome_remetente;
$email->Subject = $assunto;
$email->IsHtml(true);
$email->AddAddress($para);
$email->Body = $msg;

if(!$email->send()){
    //return false;
    die(var_dump($email->ErrorInfo));
} else {
    return true;
}
  • you are testing this code on a server or on your computer?

  • I’m testing it locally.

  • Managed to solve @Leofelipe?

  • For min was not working at all until I disabled Avast, Success.

4 answers

6

EDIT: Awaiting OP return after chat chat

First the gmail port is 465 and not 587

To use PHP Mailer with gmail you must do it this way

$mail= new PHPMailer;
$mail->IsSMTP();        // Ativar SMTP
$mail->SMTPDebug = false;       // Debugar: 1 = erros e mensagens, 2 = mensagens apenas
$mail->SMTPAuth = true;     // Autenticação ativada
$mail->SMTPSecure = 'ssl';  // SSL REQUERIDO pelo GMail
$mail->Host = 'smtp.gmail.com'; // SMTP utilizado
$mail->Port = 465; 
$mail->Username = 'seu email';
$mail->Password = 'sua senha';
$mail->SetFrom('seu email', 'seu nome(ou qualquer coisa que quiser)');
$mail->addAddress('email do destinatario','qualquer coisa que quiser');
$mail->Subject=("Assunto");
$mail->msgHTML("Sua mensagem");
if ($mail->send()){
    $ok = true;
}else{
    $ok = false;
}  

This is the code I use for gmail smtp and has always worked...

  • Hi @Rodrigoborth, I put a comment in the code saying that I tried both with port 587 and 465, of the 2 forms has brought the same error message. I also used Smtpsecure as both tls and ssl, same thing. Now I forgot to comment that I am testing locally, will there be problem?

  • No problem, you read the part where changing the SMTPDebug = false;? this is very important for gmail, if it is active gmail will not send @Leofelipe

  • I modified getting SMTPDebug = false;. Still the error message appears: SMTP Error: Could not connect to SMTP host.

  • @Leofelipe puts debug=2 and posts the error message, so it comes more complete so we can help you

  • Dude, continues the same error message. I gave a var_dump() on the object. I will update the post with the result.

  • @Leofelipe you are using the same email at $mail->SetFrom and $mail->Username?

  • @Rodrigoborth see the edition I made in your reply and fix the $mail->Subject line, ok ? []s!

  • @I don’t understand what you mean by que sintaxe é essa?

  • @Leofelipe do not know how it is in other versions, but in my addAddress is with minuscule letter, see if this is not giving problem too

  • @Rodrigoborth in your code is $mail->Subject=("Subject"); so I want to understand whether you are assigning value to Subject or calling a method but forgot an EQUAL in the middle. Your code should not be $mail->Subject="Subject"; ?

  • @gpupo the only difference between what you wrote and what I wrote is the use of the parentheses "( )" that do not influence... in this case I am assigning a value to a public variable of the class ... it is the same case of include ('file'); or include 'file';

Show 7 more comments

2

  • 1

    I had this problem and needed to activate this gmail feature after sending normally.

0


In the end, the problem was on account of the Server of the company that was blocking in some way. admin pulled the strings on the server and worked.

0

Change the door to 587 and the connection to ssl

<?php
  header('Content-Type: text/html; charset=UTF-8');

//======================================================================
// CONFIGURAÇÕES DE ENVIO
//======================================================================
      $dispatcher       = array(
        "smtp_prefix"   => "smtp", //Apenas o prefixo, ex: smtp, caso: smtp.dominio.com.br
        "port"          => "587",
        "subject"       => "assunto_email", //Assunto do e-mail
        "from"          => "[email protected]", //Email remetente
        "from_name"     => "seu_nome", //Nome do remetente
        "from_password" => "sua_senha", //Senha rementente
        "to"            => "email_destinario"); //Destinatario


//======================================================================
// CORPO DO EMAIL
//======================================================================

  $message = 'Essa mensagem é um email de teste, caso tenha recebido está tudo ok!';

//======================================================================
// [FIM] CORPO DO EMAIL
//======================================================================



  include_once("./phpmailer/class.phpmailer.php");
  $mail = new PHPMailer();
  $mail->IsSMTP();
  $mail->SMTPSecure = 'ssl';    // SSL REQUERIDO pelo GMail
  $mail->Host = "{$dispatcher["smtp_prefix"]}.".substr(strstr($dispatcher["from"], '@'), 1);
  $mail->SMTPDebug = 0; // 1 = erros e mensagens || 2 = apenas mensagens
  $mail->SMTPAuth = true;
  $mail->Port = $dispatcher["port"];
  $mail->Username = $dispatcher["from"];
  $mail->Password = $dispatcher["from_password"];

  $mail->SetFrom($dispatcher["from"], $dispatcher["from_name"]);
  $mail->Subject = $dispatcher["subject"];
  $mail->MsgHTML($message);
  $mail->AddAddress($dispatcher["to"]);
  $mail->CharSet="UTF-8";

  if(!$mail->Send()) {
    $mensagemRetorno = 'Erro ao enviar e-mail: '. print($mail->ErrorInfo);
  } else {
    //Exemplo resposta usando JavaScript
    $sucesso = '<script> document.write("E-mail enviado com sucesso!"); </script>';
    echo $sucesso;
  }

?>

Information about door 587:

Services like Gmail, Yahoo! and Hotmail will be affected? There will be changes only for those who use email reader programs, those who use these services via Webmail need not change the configuration. All these email providers already offer the submission service on the port 587/TCP. Source: Antispam.BR

  • gmail portal is not 465?

  • It works with the door 587, defined as the standard here for Brazil: See more... or Google Guide

  • I added in the answer too, it seems that not everyone knows the changes.

  • I had already seen this, however, the 587 does not work for me... I can only use gmail with port 465, in the rest of the providers use the 587 normally

  • 1

    Try to check if there is any program preventing, you can test port 587 by performing a telnet: Door response test 587

  • @Leofelipe take a look at those comments, it might help you

  • Well, I think this can help, even if I’m talking about Gmail: in cPanel port 587 is used for communications without the SSL layer and port 465 is for the opposite, I mean, I think the most correct thing is to use port 465 together with the SSL layer, since both are used by Gmail

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.