Conversion from php form to smtp

Asked

Viewed 63 times

0

The thing is, my form he didn’t have authentication, but the client server requires authentication, I made him authenticate, but now he doesn’t send. could they point out to me the mistakes so that I could correct them?

OLD PHP:

<?php
// Check for empty fields
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)){
echo json_encode(array('error'=>'true'));
return false;
}

$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];

$lastname = $_POST['lastname'];
$phone = $_POST['phone'];
$subject = ($_POST['subject'] ? $_POST['subject'] : "Website Contact   Form:  $name");



// Create the email and send the message
$to = '[email protected]';// Add your email address inbetween the ''  replacing [email protected] - This is where the form will send a message to.
$email_subject = $subject;
$email_body = "You have received a new message from your website   contact form.\n\n"."Here are the details:\n\nName: $name\n\nLast Name:     $lastname\n\nEmail: $email_address\n\nPhone:  $phone\n\nMessage:\n$message";
$headers = "From: [email protected]\n"; // This is the email address the generated message will be from. We recommend using something like [email protected].
$headers .= "Reply-To: $email_address"; 
mail($to,$email_subject,$email_body,$headers);
echo json_encode(array('success'=>'true'));
return true;            
?>

PHP New:

<?php
ini_set('display_errors', '1');
header("Content-Type: application/json; charset=utf-8");
require("phpmailer/class.phpmailer.php");
require("phpmailer/class.smtp.php");

// Check for empty fields
if(empty($_POST['name']) || empty($_POST['email']) ||   empty($_POST['message']) ||     !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)){
echo json_encode(array('error'=>'true'));
return false;
}

$mail = new PHPMailer();

$mail->IsSMTP();
$mail->SMTPAuth = true; // Usar autenticação SMTP (obrigatório para smtp.seudomínio.com.br)
$mail->Username = '[email protected]'; // Usuário do servidor SMTP (endereço de email)
$mail->Password = '*********'; // Senha do servidor SMTP (senha do email usado)

$mail->From = "[email protected]"; // Seu e-mail
$mail->Sender = "[email protected]"; // Seu e-mail
$mail->FromName = "Dimasa VW"; // Seu nome

$mail->AddAddress('[email protected]', 'Dimasa');

$mail->IsHTML(true);

$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];

$lastname = $_POST['lastname'];
$phone = $_POST['phone'];

$mail->Subject = "Contato a partir do site Dimasa VW";

$message = "
<html>
    <head>
        <title>Contato a partir do site Dimasa VW</title>
    </head>
    <body>

        <p>
            Nome: $name<br>

            Email: $email_address<br>

            Telefone: $phone<br>

            Mensagem: $message
        </p>
    </body>
</html>
";

$mail->Body = $message;
$xx = $mail->Send();

$mail->ClearAllRecipients();
$mail->ClearAttachments();

if($xx){
echo json_encode(array('success'=>'true'));
return true;
}           
?>

The script I didn’t change, I’m using the same for the new:

$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
    // additional error messages or events
},
submitSuccess: function($form, event) {
    event.preventDefault(); // prevent default submit behaviour
    // get values from FORM
    var topic = $("select#user-topic").val();
    var name = $("input#user-name").val();
    var email = $("input#user-email").val();
    var phone = $("input#user-phone").val();
    var message = $("textarea#user-message").val();
    var firstName = name; // For Success/Failure Message
    // Check for white space in name for Success/Fail message
    if (firstName.indexOf(' ') >= 0) {
        firstName = name.split(' ').slice(0, -1).join(' ');
    }
    $.ajax({
        url: "../../mail/contact_me.php",
        type: "POST",
        dataType: 'json',
        data: {
            topic: topic,
            name: name,
            email: email,
            phone: phone,
            message: message
        },
        cache: false,
        success: function(data) {
            if(data.error){
                // Fail message
                $('#success').html("<div class='alert alert-danger'>");
                $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>");
                $('#success > .alert-danger').append("<span>Perdão " + firstName + ", parece que ocorreu uma falha no envio, tente novamente!</span>");
                $('#success > .alert-danger').append('</div>');
                //clear all fields
                $('#contactForm').trigger("reset");
            }
            else if(data.success){
                // Success message
                $('#success').html("<div class='alert alert-success'>");
                $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;").append("</button>");
                $('#success > .alert-success').append("<span>Sua mensagem foi enviada com sucesso </span>");
                $('#success > .alert-success').append('</div>');
                //clear all fields
                $('#contactForm').trigger("reset");
            }
        }
    })
},
filter: function() {
    return $(this).is(":visible");
},
});
});


/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});

If you have to change the script, please let me know as well.

  • 1

    Downvoter, could you explain to Pedro what he did wrong?

1 answer

1

Attention should be paid to smtp authentication:

$mail->SetLanguage("br");
$mail->IsSMTP(); // Define que a mensagem será SMTP
$mail->Host = smtp.seudomínio.com.br; // Endereço do servidor SMTP (caso queira utilizar a autenticação, utilize o host smtp.seudomínio.com.br)
$mail->SMTPAuth = true; // Usar autenticação SMTP (obrigatório para smtp.seudomínio.com.br)
$mail->SMTPSecure = ''; // Protocolo ssl ou tls
$mail->Port = 'port'; // Porta do servidor a ser usado
$mail->Username = ''; // Usuário do servidor SMTP (endereço de email)
$mail->Password = ''; // Senha do servidor SMTP (senha do email usado)

Adding the missing lines, you must authenticate quietly.

Browser other questions tagged

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