0

I'm trying to send email with an Ajax form and swiftmailer. It works in local but not in production.

When contact_me.php takes parameters not from form but written explicitly the email is sent even from the server so I think Swiftmailer is working.

contact_me.js

// Contact Form Scripts

$(function() {

    $("#contactForm input,#contactForm 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 name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#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",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message
                },
                dataType: "text",
                cache: false,
                success: function() {
                    // Success message       
                },
                error: function() {
                    // Fail message                    
                },
            });
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});


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

contact_me.php

<?php
// Autoload for swiftmailer
require_once '../vendor/autoload.php';

// Check for empty fields
if(empty($_POST['name'])      ||
   empty($_POST['email'])     ||
   empty($_POST['phone'])     ||
   empty($_POST['message'])   ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
   echo "No arguments Provided!";
   return false;
   }


$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));

// Create the email and send the message
$email_subject = "TrustPair nouveau contact :  $name";
$email_body = "New form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";

// Add here swiftmailer code, need to return true
// Create the Transport
$transport = (new Swift_SmtpTransport('mail.gandi.net', 465, "ssl"))
  ->setUsername('name@domain.com')
  ->setPassword('password')
;

// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);

// Create the message
$message = (new Swift_Message())
    // Give the message a subject
    ->setSubject($email_subject)
    // Set the From address with an associative array
    ->setFrom(['noreply@domain.com' => 'Domain no reply'])
    // Set the To addresses
    ->setTo(['firstmailto@gmail.com', 'secondmailto@gmail.com'])
    // Give it a body
    ->setBody($email_body)
    ;

// Send the message
$result = $mailer->send($message);
echo $result;
// result is equal to the nbr of message recipients

if ($result == 0) {
    return false;
} else {
    return true;
}


?>
user3707264
  • 318
  • 4
  • 15
  • does there any errors ? – hassan Jun 18 '17 at 08:06
  • jquery.min.js:4 POST http://example.com/mail/contact_me_test.php 405 (Not Allowed) send @ jquery.min.js:4 ajax @ jquery.min.js:4 submitSuccess @ contact_me.js:22 (anonymous) @ jqBootstrapValidation.js:76 dispatch @ jquery.min.js:3 r.handle @ jquery.min.js:3 – user3707264 Jun 18 '17 at 08:16
  • Your code is `url: "././mail/contact_me.php"` and the error says: `/mail/contact_me_test.php`. It's not even trying to post to the same file? (and you should also remove the `././mail/...` in front of the URL, and use relative from the root: `/mail/...`) – M. Eriksson Jun 18 '17 at 08:21
  • I replaced contact_me.php to a new file contact_me_test.php where I don't use input from the form but values that are in the code. When I run "php contact_me_test.php" the email are sent. I changed the path to relative, I always have the same 405 error. – user3707264 Jun 18 '17 at 08:30
  • I don't know if it helps but the code works when I use wamp Virtual Host in local. However if I use browserSync (localhost), I have a 404 error POST http://localhost:3000/mail/contact_me.php 404 (Not Found), I don't run browserSync in prod so I'm not sure of how it can help. – user3707264 Jun 18 '17 at 08:41

1 Answers1

3

Nginx server doesn't allow POST request with static page (ie. *.html).

There are hacks to handle the problem. In my case, it fix the 405 error but the emails weren't send.

The solution was to change the index.html to index.php, be sure to adapt your Nginx configuration to reflect this changes.

user3707264
  • 318
  • 4
  • 15