Otto Otto - 2 months ago 25
PHP Question

PHPMailer returns SMTP error with Ajax

I have a simple form set up with AJAX and PHP. This all works when I type the unix command

php send_nl.php
, but every time it returns a SMTP error from the ajax request.


Message could not be sent.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting


newsletter.php

$(document).ready(function() {
$('#risultato tbody').on( 'click', '.invianl', function (e) {
e.preventDefault();

var jqxhr = $.ajax({
url: includes/api_send_nl.php,
type: "POST",
data: {}
}).done(function(json) {
alert(json);
}).fail(function(data) {
alert( "error" +data );
});

console.log(jqxhr);
return false;
});
});


includes/api_send_nl.php

require "common.php" ;
require 'PHPMailer/PHPMailerAutoload.php';

$id = 2;
//$email_id=$_GET['email_id'];

//function sendMail($id){
$mail = new PHPMailer;
$mail->isSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = 'localhost';
$mail->SMTPAuth = false;
$mail->Port = 25;

//$mail->SMTPDebug = 1;

$stmt=$db->prepare("select * from newsletter_email where email_id='$id'");
if (!$stmt) {
log_msg($db->error);
die();
}
if (!test_execute($stmt->execute())) die("ERRORE QUERY 2");
$newsletter=fetchArray($stmt);
$stmt->close();
$newsletter=$newsletter[0];

$mail->setFrom($newsletter['from_email'], $newsletter['from_name']);
$mail->addAddress('info@mydomain.com');
$mail->addReplyTo($newsletter['replyto_email'], $newsletter['replyto_name']);

$mail->isHTML(true);

$mail->Subject = $newsletter['subject'];
$mail->Body = $newsletter['body'];
$mail->AltBody = 'Se non riesci a visualizzare la mail, clicca qui';

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

Answer

Settings $mail->SMTPDebug = 2 I discovered this issue:

PHPMailer SMTP -> ERROR: Failed to connect to server: Permission denied (13)

And I solved with: https://gistpages.com/posts/phpmailer_smtp_error_failed_to_connect_to_server_permission_denied_13_fix

Comments