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.
Related
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;
}
Is there something I'm missing? I've searched high, and low, and I'm not sure what's wrong with my code. Also is it that I'm using public, rather than mail?
<?php
require_once('phpmailer.php');
class Mail extends PhpMailer
{
// Set default variables for all new objects
public $mail = IsSMTP;
public $From = 'register#lolvoid.net23.net';
public $FromName = SITETITLE;
public $Host = 'smtp.gmail.com';
public $port = 587;
public $Mailer = 'smtp';
public $SMTPAuth = true;
public $Username = 'email#gmail.com';
public $Password = 'password';
public $SMTPSecure = 'tls';
public $WordWrap = 75;
public function subject($subject)
{
$this->Subject = $subject;
}
public function body($body)
{
$this->Body = $body;
}
public function send()
{
$this->AltBody = strip_tags(stripslashes($this->Body))."\n\n";
$this->AltBody = str_replace(" ", "\n\n", $this->AltBody);
return parent::send();
}
}
This is my current code, and the issue hasn't been resolved. Any new ideas?
Change port to secured one for SMTP: 465
Port should be 587 instead of 4587.
Here are the default Gmail SMTP settings;
Gmail SMTP server address: smtp.gmail.com
Gmail SMTP username: Your
full Gmail address (e.g. yourusername#gmail.com)
Gmail SMTP password: Your Gmail password
Gmail SMTP port (TLS): 587
Gmail SMTP port (SSL): 465
Gmail SMTP TLS/SSL required: yes
and could you please change the line
public $mail = 'IsSMTP()'
with the following:
public $mail = IsSMTP();
Most probably a port.
public $port = '4587';
if you tried configuring your SMTP server on port 465 (with SSL/TLS)
and port 587 (with STARTTLS), but are still having trouble sending
mail, try configuring your SMTP to use port 25 (with SSL/TLS).
Apple Mail users: At times, Mail may misinterpret your SMTP server
settings. If you currently have 'smtp.gmail.com:username#gmail.com' in
the 'Outgoing Mail Server:' field of your settings, please try
changing the field to 'smtp.gmail.com' and saving your settings.
https://support.google.com/mail/answer/78775?hl=en
You mixed 465 and 587 ports.
If it still does not work, you can try debugging connection. See PHPMailer only sends email when SMTPDebug = true for example.
Also, from documentation:
/**
* SMTP class debug output mode.
* Debug output level.
* Options:
* * `0` No output
* * `1` Commands
* * `2` Data and commands
* * `3` As 2 plus connection status
* * `4` Low-level data output
* #var integer
* #see SMTP::$do_debug
*/
public $SMTPDebug = 0;
Use it to find out what problem may be. It will tell you where it stops.
I have a config array with some smtp settings.
I am looking for a way to extend Swiftmailer to auto fill in these details.
I cannot find anything about extending swiftmailer. I did found some information about plugins, but these existing plugins of swiftmailer won't tell me anything.
// automatic use smtp.domain.com, username, password ??
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Test')
->setFrom(array('mail#domain.com' => 'from user'))
->setTo(array('mail#domain.com' => 'from user'))
->setBody('Body')
;
$result = $mailer->send($message);
Can anyone tell me how to do this?
I don't see why you should extend SwiftMailer for that requirement. It's much easier to create a class that handles the preparation e.g.
class SwiftMailerPreparator {
private $mailer;
public __construct(Swift_Mailer $mailer) {
$this->mailer = $mailer;
}
public function prepare(array $settings) {
// do your thing here
}
}
Also since SwiftMailer is opensource you can just look at the code and see how it works.
You could wrap everything into a service class like this:
class MyMailerAssistant
{
/**
* Service method to fastly send a message
* #param $subject
* #param $body
*/
public static function sendMessage($subject, $body)
{
// automatic use smtp.domain.com, username, password ??
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Test')
->setSubject($subject)
->setFrom(array('mail#domain.com' => 'from user'))
->setTo(array('mail#domain.com' => 'from user'))
->setBody($body);
$result = $mailer->send($message);
}
}
and calling it simply in this way:
MyMailerAssistant::sendMessage('Hello', 'This is the email content');
Anyway I strongly discourage you inserting your configuration into a method, I would always load it from a modular external configuration file.
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
));
};
I know how to use SMTP with PHPMailer:
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "mail.yourdomain.com"; // sets the SMTP server
$mail->Username = "yourname#yourdomain"; // SMTP account username
$mail->Password = "yourpassword"; // SMTP account password
And it works fine. But my question is:
How can I configure PHPMailer to use these settings on default, so that I do not have to specify them each time I want to send mail?
Create a function, and include / use it.
function create_phpmailer() {
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "mail.yourdomain.com"; // sets the SMTP server
$mail->Username = "yourname#yourdomain"; // SMTP account username
$mail->Password = "yourpassword"; // SMTP account password
return $mail;
}
And call create_phpmailer() to create a new PHPMailer object.
Or you can derive your own subclass, which sets the parameters:
class MyMailer extends PHPMailer {
public function __construct() {
parent::__construct();
$this->IsSMTP(); // telling the class to use SMTP
$this->SMTPAuth = true; // enable SMTP authentication
$this->Host = "mail.yourdomain.com"; // sets the SMTP server
$this->Username = "yourname#yourdomain"; // SMTP account username
$this->Password = "yourpassword"; // SMTP account password
}
}
and use new MyMailer().
Can I not just edit the class.phpmailer.php file?
It's best not to edit class files themselves because it makes the code harder to maintain.
You can also use this hook:
/**
* Fires after PHPMailer is initialized.
*
* #since 2.2.0
*
* #param PHPMailer &$phpmailer The PHPMailer instance, passed by reference.
*/
do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
From the source of the wp_mail function itself to modify the phpmailer class directly.