Search code examples
javascriptphpsendmailvps

Sendmail problem with js + php on debian 9


I got actually a problem to send a mail with my VPS server. My server have PHP and sendmail installed.

I try to send an email from an HTML form which is checked in JS then sent in HTML, the request launches well but nothing is sent.

My JS code :

submitMail() {
      const emailValue = document.getElementById('mail').value;
      const subjectValue = document.getElementById('subject').value;
      const messageValue = document.getElementById('text').value;
      const xhr = new XMLHttpRequest();
      xhr.open('POST', 'https://ag-dev.fr/mailform.php', true);
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4 && xhr.status === 200) {
          this.sendComplet();
        }
      };
      xhr.send(JSON.stringify({
        email: emailValue,
        subject: subjectValue,
        message: messageValue,
      }));
    },

My PHP code :

<?php
  if (!empty($_POST['message']))
  {
      $to = '[email protected]';
      $from = $_POST['email'];
      $subject = $_POST['subject'];
      $message = $_POST['message'] . "\n\n\n\n Ceci est un message envoyé depuis le formulaire de contact. Pour répondre à ce mail, envoyez un mail à l'adresse suivante : " . $_POST['email'];
      $headers  = 'MIME-Version: 1.0\r\n';
      $headers .= 'Content-type: text/html; charset=iso-8859-1\r\n';
      $headers .= 'To: Guyomar Alexis <[email protected]>\r\n';
      $headers .= 'From: ' . ' <' . $from . '>\r\n';
      mail($to,$subject,$message,$headers);
  }
?>

I run a test on my command line server with sendmail and I receive the mail with no problem. I think my code or my configuration server got a problem.

If anyone has any idea where this may have come from ...


Solution

  • Thank you @ADyson for your JSON POST with PHP link. I solve my problem like this :

    <?php
      $data = json_decode(file_get_contents('php://input'), true);
      if (!empty($data))
      {
          $to = '[email protected]';
          $from = $data['email'];
          $subject = utf8_decode($data['subject']);
          $message = utf8_decode($data['message']) . utf8_decode("\n\n\n\n Ceci est un message envoyé depuis le formulaire de contact. Pour répondre à ce mail, envoyez un mail à l'adresse suivante : " . $from);
          $headers  = 'MIME-Version: 1.0\r\n';
          $headers .= 'Content-type: text/html; charset=utf-8\r\n';
          $headers .= 'To: Guyomar Alexis <[email protected]>\r\n';
          $headers .= 'From: ' . ' <' . $from . '>\r\n';
          mail($to,$subject,$message,$headers);
      }
    ?>
    

    now all run good.