How to send email with phpMailer and fetch API

23 Views Asked by At

I'm trying to create a sending email button on my website. You can see it there :text I'm using the fetch API that captures information on click, and sends it to my phpEmail.php file which is supposed to send me an email.

To test on my local I use mailtrap.io and the reception is ok, and I get the response of my fetch in my log. But when I'm trying in prod, even if I have the good params and credentials Ionos (I've alradeay check with them), the reception doesn't work anymore and the fetch response is "empty string".

This is my js code :

async function sendEmail() {

    var url = 'https://julietcolombe.fr/wp-content/themes/julietcolombe/sendEmail.php';
    var drawingData = canvas.toDataURL();
    var image = encodeURIComponent(drawingData);

    var formData = new FormData();
    formData.append('drawingData', image);

    fetch(url, { method: 'POST', body: formData })
        .then(function (response) {
            return response.text();
        })
        .then(function (body) {
            console.log(body);
        });

}

var sendEmailButton = document.getElementById('envoyerBtn');
sendEmailButton.addEventListener('click', function () {
    sendEmail();
});

And this is my sendEmail.php for prod:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require \vendor\autoload.php';

    try {

        $mail = new PHPMailer(true);
        $mail->isSMTP();
        $mail->SMTPAuth = true;
        $mail->Host = "smtp.ionos.com";
        $mail->Port = 587;
        $mail->Username = "****";
        $mail->Password = "****";
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    
        $mail->From = "****@julietcolombe.fr";
        $mail->addAddress("****@julietcolombe.fr");
    
        $mail->isHTML(true);
        $mail->Subject = "Subject Text";
        $mail->Body = "<i>Mail body in HTML</i>";
        $mail->AltBody = "This is the plain text version of the email content";
    
        $mail->CharSet = 'UTF-8';
        $mail->Encoding = 'base64';
    
        $mail->send();
    
        echo "OK";
    } catch (Exception $e) {
        echo "Mailer Eror : {$e->getMessage()}";
    }
}
0

There are 0 best solutions below