Send email with PHP

Asked

Viewed 762 times

-4

Guys, someone take a step by step of how I do in PHP to send emails, Phpmailer or mail(), whatever, sending the email matters, I’ve tried everything and not getting it at all.

Here’s the code I’m using:

if (isset($_POST["recovery_pass"]))
{
  if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
  {
    $email = $_POST["email"];
  }
  else
  {
    echo "email is not valid";
        exit;
    }

  // Check to see if a user exists with this e-mail
    $query = $conexao->prepare('SELECT email FROM users WHERE email = :email');
    $query->bindParam(':email', $email);
    $query->execute();
    $userExists = $query->fetch(PDO::FETCH_ASSOC);
    $conexao = null;

    if ($userExists["email"])
    {
        // Create a unique salt. This will never leave PHP unencrypted.
        $salt = "498#2D83B631%3800EBD!801600D*7E3CC13";

        // Create the unique user password reset key
        $password = hash('sha512', $salt.$userExists["email"]);

        // Create a url which we will direct them to reset their password
        $pwrurl = "$linkSite/recovery_pass/$password";

        require ("phpmailer/PHPMailerAutoload.php");
        // Inicia a classe PHPMailer
        $mail = new PHPMailer;

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

        // Define o remetente
        // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
        $mail->setFrom = ('[email protected]'); // Seu e-mail

        // Define os destinatário(s)
        // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
        $mail->AddAddress($email);

        $mail->IsHTML(true); // Define que o e-mail será enviado como HTML
        //$mail->CharSet = 'iso-8859-1'; // Charset da mensagem (opcional)
        $mail->Subject = "Recuperação de senha"; // Assunto da mensagem
        $mail->Body = "Este é o corpo da mensagem de teste, em ".$pwrurl." <b>HTML</b>!  :)";
        $mail->AltBody = "Este é o corpo da mensagem de teste, em Texto Plano! \r\n :)";

        // Envia o e-mail
        $enviado = $mail->Send();

        // Limpa os destinatários e os anexos
        $mail->ClearAllRecipients();

        // Exibe uma mensagem de resultado
        if ($enviado) {
            echo "E-mail enviado com sucesso!";
        } else {
            echo "Não foi possível enviar o e-mail.";
            echo "<b>Informações do erro:</b> " . $mail->ErrorInfo;
        }
        }
        else
        echo "No user with that e-mail address exists.";
        }
?>

<form action="#" method="post" enctype="multipart/form-data" class="form-horizontal">

<fieldset class="form-group">
    <label for="email">Email</label>
    <input type="email" class="form-control" name="email" placeholder="Email" maxlength="70" size="70" required>
</fieldset>

<input type="submit" class="btn btn-primary" name="recovery_pass" value="Recovery">
  • 2

    http://answall.com/search?q=email+php+is%3Aquestion

  • @Williamalvares looking at your code, there’s nothing wrong with it. This matches the example of phpmailer https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps for what appears in $mail->Errorinfo when you try to send. Also have to see if you’ve enabled SMTP in your gmail.

  • Friend activates Debug to facilitate identification of the problem. $mail->Smtpdebug = 2; // Enables SMTP debug information (for testing) // 1 = errors and messages // 2 = messages only

  • @Rafaelmenabarreto Appeared all this: 2016-01-22 19:13:58 SMTP ERROR: Failed to connect to server: php_network_getaddresses: getaddrinfo failed: Name or service not known (0) 2016-01-22 19:13:58 SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting Could not send e-mail: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

  • @Williamalvares error message points to a fault in your network. The computer where you run this code is with internet, DNS working? Has some door lock or firewall?

  • @Rafaelmenabarreto Are they stirring I think, added SSL, interfere ?? I think I’ll take some time, until SSL is added and added the Dedicated IP..

  • William Alvares, When asking a question/questions try to give more significant details so that we can understand your problem and can help you solve, Always try to inform: used code, error message, objective, structure/ place where you are trying. This makes it easier for you to receive a solution and avoid having your question closed. Tip there.

Show 4 more comments

2 answers

1


Got it, still below the code working!

require 'phpmailer/PHPMailerAutoload.php';

        $mail = new PHPMailer;

        //$mail->SMTPDebug = 3;

        $mail->isSMTP();
        $mail->Host = 'smtp.live.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'meuemailoutlook';
        $mail->Password = 'secret';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;

        $mail->setFrom('meuemailoutlook', '5tars');
        $mail->addAddress($email);

        $mail->isHTML(true);
        $mail->CharSet = 'iso-8859-1';

        $mail->Subject = 'Recuperação de senha';
        $mail->Body    = 'Este é o corpo da mensagem de teste, em '.$pwrurl.' <b>HTML</b>!  :)';
        $mail->AltBody = 'Este é o corpo da mensagem de teste, em Texto Plano! \r\n :)';

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

1

Your problem seems to be because you have not configured php.ini. search the archive for [mail function] ; For Win32 only. SMTP = localhost smtp_port = 25

In SMTP = you indicate the SMTP server you will use to send the message.

This link can help :http://www.criarweb.com/faq/configurar-php-ini-smtp.html

  • While this link may answer the question, it is best to include the essential parts of the answer here and provide the link for reference. Replies per link only can be invalidated if the page with the link is changed. - From Review

  • Sorry Ricardo, I’m new here.

Browser other questions tagged

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