500 internal server error when doing ajax request - php

I'm having trouble investigating an 500 Internal Server Error I get when trying to do an AJAX request ( I'm doing a "PUT" / "GET" ) on my server.
Locally it runs without any issues and it responds, but after I uploaded the content on the server it doesn't, as if the file / folder wouldn't be there.
The host is running on Apache with PHP at least version 5.3.0 since I last checked. I get the error when trying to use the footer newsletter subscribe.
My index file which is requested when doing the AJAX looks like the following :
<?php
/*
* Import PHPMailer Class
*/
require("phpmailer/class.phpmailer.php");
/*
* Decode JSON Data
*/
$request = json_decode(file_get_contents("php://input"), true);
/*
* Check Valid Email Address
*/
if (!filter_var($request["Email"], FILTER_VALIDATE_EMAIL)) {
echo json_encode([
"error" => true,
"message"=> "You must enter a valid email address"
]);
return false;
};
/*
* Instantiate PHPMailer Class
*/
$mailer = new PHPMailer();
/*
* Set Reply Settings
*/
$reply_email = "no-reply#barbershoppen.dk";
$reply_name = "Barber Shoppen";
/*
* Specific PHPMailer Settings
*/
$mailer->IsSMTP(); /* SMTP Usage */
$mailer->SMTPAuth = true; /* SMTP Authentication */
$mailer->SMTPSecure = "ssl"; /* Sets Servier Prefix */
$mailer->Host = "smtp.gmail.com"; /* SMTP Server */
$mailer->Port = 465; /* SMTP Port */
$mailer->Username = "rolandeveloper#gmail.com"; /* SMTP Account Username */
$mailer->Password = "333333333"; /* SMTP Account Password */
/*
* Email Settings
*/
$mailer->SetFrom($reply_email, $reply_name);
$mailer->AddReplyTo($reply_email, $reply_name);
$mailer->AddAddress($request["Email"]);
$mailer->Subject = "Barber Shoppen [ Confirmation Email ]";
$mailer->Body = "You have successfully subscribed to our newsletter";
$mailer->isHTML(true);
/*
* Send Email
*/
if($mailer->Send()) {
echo json_encode([
"error" => false,
"message"=> "You have successfully subscribed"
]);
} else {
echo json_encode([
"error" => true,
"message"=> $mailer->ErrorInfo
]);
};
?>
I would appreciate some help or some pointers in which directions I should head and fix this error.

You want to pass in a PHP-style array instead of a javascript-style array into json_encode:
if (!filter_var($request["Email"], FILTER_VALIDATE_EMAIL)) {
echo json_encode(array(
"error" => true,
"message"=> "You must enter a valid email address"
));
return false;
};
And:
if($mailer->Send()) {
echo json_encode(array(
"error" => false,
"message"=> "You have successfully subscribed"
));
} else {
echo json_encode(array(
"error" => true,
"message"=> $mailer->ErrorInfo
));
};

Related

Why can't I send the mail from the form with symfony?

I am building this website and on one of the pages I have a contact form from which the user should be able to send a message to us.
.env :
###> symfony/google-mailer ###
# Gmail SHOULD NOT be used on production, use it in development only.
MAILER_DSN=gmail://myEmail.com:myPassword#default?verify_peer=0
###< symfony/google-mailer ###
mailer.yaml :
framework:
mailer:
dsn: '%env(MAILER_DSN)%'
the code that is supposed to send the mail :
/**
* #Route("/contact", name="api_mail")
*/
public function mailAPI(Request $request, MailerInterface $mailer)
{
if($_SERVER["REQUEST_METHOD"] == "POST"){
$name = $_POST["Name"];
$mail = $_POST["Mail"];
$game = $_POST["Game"];
$category = $_POST["Categ"];
$message = $_POST["Msg"];
$email = (new Email())
->from($mail)
->to('myEmail#gmail.com')
->subject('Testing the mail sender from symfony.')
->text($message)
->html('<p> This is a message </p>');
$mailer->send($email);
}
return $this->render('default/index.html.twig', [
'controller_name' => 'DefaultController',
]);
}
}
At first I used mailCatcher and it caught the mails, now I configured the gmail thingy to send the mails via the gmail transport but it doesn't do anything.

CodeIgnititer 4: Unable to send email using PHP SMTP

I read all the other answers related to that question, but none of them help.
When I try to run the following setup either on my localhost or my production server, I get the following error message:
Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method.
I installed CodeIgniter 4 and added the following to .env:
email.production.protocol = smtp
email.production.SMTPHost = my.server.com
email.production.SMTPUser = My#Mail.com
email.production.SMTPPass = MyPassword
email.production.SMTPCrypto = ssl
email.production.SMTPPort = 465
email.production.SMTPFromName = "Foo Bar"
For port 465 or 587 and crypto ssl or tsl I tried every possible option.
In the app/Config/Email.php the setting public $newline = "\r\n"; is already set (Suggestion coming from here.
I am successfully able to run
telnet my.server.com 465
telnet my.server.com 587
Then I added the following code to the end of app/Config/Email.php:
public function __construct()
{
$this->protocol = $_ENV['email.production.protocol'];
$this->SMTPHost = $_ENV['email.production.SMTPHost'];
$this->SMTPUser = $_ENV['email.production.SMTPUser'];
$this->SMTPPass = $_ENV['email.production.SMTPPass'];
$this->SMTPPort = $_ENV['email.production.SMTPPort'];
$this->SMTPCrypto = $_ENV['email.production.SMTPCrypto'];
$this->fromEmail = $_ENV['email.production.SMTPUser'];
$this->fromName = $_ENV['email.production.SMTPFromName'];
}
In my Controller I added a function with:
$email = \Config\Services::email();
$email->setSubject("Test");
$email->setMessage("Test");
$email->setTo("myaddress#example.com");
if ($email->send(false)) {
return $this->getResponse([
'message' => 'Email successfully send',
]);
} else {
return $this
->getResponse(
["error" => $email->printDebugger()],
ResponseInterface::HTTP_CONFLICT
);
}
Calling this function produces the error message described above.
I assume that this has nothing to do with the server configuration as the error message describes, because the is happening on localhost and production.
Update: This must have something to do with the CI setup. No matter what server I try, even with completely incorrect values (e.g. incorrect password) the error is exactly the same.
I usually use smtp gmail to send email for my client. the most important of 'send email by smtp gmail' is you must update your Gmail Security rules:
In your Gmail Account, click on Manage your Google Account
click tab Security
then, turn 'less secure app access' to 'ON'
After that, you set your 'app\config\EMail.php' like this:
public $protocol = 'smtp';
public $SMTPHost = 'smtp.gmail.com';
public $SMTPUser = 'your.googleaccount#gmail.com';
public $SMTPPass = 'yourpassword';
public $SMTPPort = 465;
public $SMTPCrypto = 'ssl';
public $mailType = 'html';
Last, you can create sendEmai function on controller like this:
$email = \Config\Services::email();
$email->setFrom('emailsender#gmail.com', 'Mr Sender');
$email->setTo('emailreceiver#gmail.com');
$email->setSubject('Test Subject');
$email->setMessage('Test My SMTP');
if (!$email->send()) {
return false;
}else{
return true;
}

Can't receive emails sent from a Codeception test

I have a local Wordpress website that sends emails successfully, however if I try to send an email from a Codeception integration test, I do not receive any emails. (By the way, I don't think the problem has to do with Wordpress, which is why I'm posting here rather than Wordpress Stack Exchange).
I've configured Wordpress like this:
add_action( "phpmailer_init", array( $this, "configure_mailer" ) );
function configure_mailer( $mailer ) {
$mailer->isSMTP();
$mailer->Host = "smtp.gmail.com";
$mailer->SMTPAuth = true;
$mailer->Username = "myemail#gmail.com";
$mailer->Password = "mypassword";
$mailer->SMTPSecure = "tls";
$mailer->Port = 587;
$mailer->IsHTML( true );
}
Now if I try to send an email with wp_mail (which internally uses a PHPMailer instance configured as above) from my Wordpress code, eg. via an API request, I do receive the email:
// This is the custom API route that sends the email
register_rest_route( "mynamespace/v1", "/send-email", [
"methods" => \WP_REST_Server::CREATABLE,
"permission_callback" => "__return_true",
"callback" => function() {
$result = wp_mail( "myemail#example.com", "Test subject", "Test message", array( "From: MySite <myemail#example.com>");
return new \WP_REST_Response( $result );
}
]);
// This is the API request
POST https://example.com/wp-json/mynamespace/v1/send-email
The above request returns true because wp_mail returns true (as it does when an email is sent successfully), and I receive the email.
If I try to send the email from a Codeception integration test, the test succeeds because wp_mail still returns true, but I do not receive the email. (The \Codeception\TestCase\WPTestCase comes from wpbrowser, a package I use for testing Wordpress with Codeception).
class EmailTest extends \Codeception\TestCase\WPTestCase {
public function testSendsEmail() {
$result = wp_mail( "myemail#example.com", "Test subject", "Test message", array( "From: MySite <myemail#mysite.com>");
$this->assertTrue( $result );
}
}

how can i use smtp config thats received from form?

i want to use config that i get from html form and i dont want to get it from config/mail.php or .env file
how can i do that in laravel 8
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from($address = 'contact#example.com', $name = $this->data['from'])
->subject($this->data['subject'])
->view('mail.view')
->smtp('mail.example.com')
->port('587')
->username('username')
->password('pass')
->smtp('mail.example.com')
->with(['message' => $this->data['message']]);
}
you can use swiftmailer to send any type of mail you want (laravel use this under the hood):
$transport = (new Swift_SmtpTransport("smtp.gmail.com", "587", "tls"))
->setUsername('username')
->setPassword('pass');
$mailer = new Swift_Mailer($transport);
$message = (new Swift_Message("subject")) // email subject
->setFrom(['contact#example.com' => "sender name"]) // sender mail and display name
->setTo("receiver#gmail.com") // replace with your receiver mail variable
->setBody("<h2>Test</h2>", 'text/html');
$result = $mailer->send($message); // send the mail
if you want to send from queue instead of in controller directly, you can create queue and pass mail parameter to queue construct

FatalThrowableError in Laravel Php mailer on live server

My laravel project php mailer function is working in local host. But in the live server it's not working:
Error:
FatalThrowableError in RegisterController.php line 75:
Class 'App\CustomClass\CMailer' not found
Here is my controller file:
enter code here
<?php
namespace App\Http\Controllers\Auth;
use App\CustomClass\CMailer;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
use RegistersUsers;
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:4|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
if ($user) {
$mailException = null;
$view = view('auth.verification', compact('user'))->render();
try {
$mail = CMailer::send('Prapti', $data['email'], 'Email verification', $view);
} catch (Exception $e) {
$mailException = true;
}
}
return $user;
}
}
enter code here
My class file:
enter code here
namespace App\CustomClass;
use PHPMailer\PHPMailer\PHPMailer;
class CMailer
{
protected static $host = "smtp.gmail.com";
protected static $port = 468;
protected static $encryption = 'tls';
protected static $username = "******";
protected static $password = '***************';
protected static $from = '**************#gmail.com';
/**
* Sending email by PHPMailer
*
* #param string $fromName
* #param string $to
* #param string $subject
* #param string $message
* #return TRUE
*/
public static function send($fromName, $to, $subject, $message)
{
$mail = new PHPMailer(true);
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = self::$host;
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = self::$port;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = self::$encryption;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for
gmail
$mail->Username = self::$username;
//Password to use for SMTP authentication
$mail->Password = self::$password;
//Set who the message is to be sent from: this is sender email
$mail->setFrom(self::$from, $fromName);
//Set who the message is to be sent to
$mail->addAddress($to, 'Test Service');
//Set the subject line
$mail->Subject = $subject;
$mail->msgHTML($message);
if (!$mail->send()) {
// return $mail;
return false;
} else {
return true;
}
}
}
** Php mailer and class is okay. I've tested by changing port but same problem. and not working in hosting. Where is the problem?
Please suggest me the solution.
You need to run composer dump-autoload to reload all missing classes.
If the same code works on your local machine, you need to run composer du command on the live server and include this command to your deployment script.

Categories