I'm new to Laravel. I wanted to send a mail to users for every time they login. I wrote the authentication logic already.
<?php
namespace App\Http\Controllers\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Events\Login;
class LoginController extends Controller
{
public function __construct(){
$this->middleware('guest')->except('logout');
}
public function index(){
return view('users.login');
}
public function login(Request $request){
$credentials = $request->only('username', 'password');
if(Auth::attempt($credentials)){
event(new Login(auth()->user()));
return redirect()->intended(route('homepage'));
}else{
return redirect()->back()->withInput()->with('error', 'Username/Password Combo Wrong!');
}
}
public function logout(){
Auth::logout();
return redirect()->route('login-form');
}
}
I wrote an event for this
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use App\User;
class Login
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
This is the event listener
<?php
namespace App\Listeners;
use App\Events\Login;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Request;
use App\Mail\UserLoggedIn;
class SendLoginNotification
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param Login $event
* #return void
*/
public function handle(Login $event)
{
Mail::send($event)->send(new UserLoggedIn($event));
}
}
I created a mail class
<?php
namespace App\Mail;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class UserLoggedIn extends Mailable
{
use Queueable, SerializesModels;
public $user;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('test#mail.com')->view('emails.users.loggedin');
}
}
I then created the view for the mail in resources/views/emails/users/loggedin.blade.php
<!Doctype html>
<html>
<head>
<title>User Logged In</title>
</head>
<body>
{{$user->name}} Logged in
</body>
</html>
But when i run try to run the login, i get an error saying invalid view
There are a couple of issues I've noticed. Currently, you're:
calling send twice in your SendLoginNotification (and you're passing the Event instead of a mailable to one of them)
not specifying who to send the mail to
also passing the $event to the mailable rather than the User
Change:
Mail::send($event)->send(new UserLoggedIn($event));
To:
Mail::to($event->user)->send(new UserLoggedIn($event->user)); //notice the "user" property.
you didn't pass any variable containing user info.
public function build()
{
$user=User::find(1);
return $this->from('test#mail.com')->view('emails.users.loggedin',compact('user'));
}
Related
Here is code that works:
Mail::to($emails)->send(new ExceptionOccurred($e));
And then I change it to:
Mail::to($emails)->queue(new ExceptionOccurred($e));
When I do I get the error:
ErrorException: Undefined property: App\Mail\ExceptionOccurred::$content in C:\inetpub\wwwroot\laravel\app\Mail\ExceptionOccurred.php:33
This is ExceptionOccurred.php:
namespace App\Mail;
use Illuminate\Bus\Queueable;
// use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class ExceptionOccurred extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($content)
{
$this->content = $content;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->markdown('mail.ExceptionOccurred')
->subject('Exception on live instance')
->with('content', $this->content);
}
}
This is the relevant portion of the exception handler:
if ( $exception instanceof Exception ) {
$e = FlattenException::create($exception);
} else {
$e = $exception;
}
$emails = json_decode( env('MAINTAINER_EMAILS') );
if (app()->environment('production') || app()->environment('testing') ) {
Mail::to($emails)->send(new ExceptionOccurred($e));
}
To re-iterate, Mail::send() works, but Mail::queue() does not. I believe the queue is set up correctly.
You have to define the content attribute before the construct, like this:
namespace App\Mail;
use Illuminate\Bus\Queueable;
// use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class ExceptionOccurred extends Mailable
{
use Queueable, SerializesModels;
public $content;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($content)
{
$this->content = $content;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->markdown('mail.ExceptionOccurred')
->subject('Exception on live instance')
->with('content', $this->content);
}
}
Reference: https://laravel.com/docs/8.x/mail#view-data
i am not able pass form data to job from controller in laravel
below is my controller
public function sendmail_action(Request $request){
try{
$data=$request->all();
$this->dispatch(new LeadSendmailJob($data));
return response()->json(['status'=>'true']);
}catch (\Exception $e){
return response()->json(['status'=>'false','msg'=>$e->getMessage()]);
}
}
below is job
<?php
namespace App\Jobs;
use App\Mail\LeadMail;
use Illuminate\Bus\Queueable;
use Illuminate\Http\Request;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Mail;
class LeadSendmailJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* #return void
*/
public $data;
public function __construct(array $data)
{
$this->data=$data;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
Mail::to('sdf#gmail.com')->send(new LeadMail($this->data));
}
}
and below is mail
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class LeadMail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public $data;
public function __construct(array $data)
{
$this->data=$data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->markdown('frontend.emails.lead-mail')
->from('info#nextaussietech.com')
->with(['message'=>$this->data->message]);
}
}
in failed job table i am getting this exception
ErrorException: Trying to get property 'message' of non-object in C:\xampp\htdocs\CRM\app\Mail\LeadMail.php:34
it works while using model data but its not working when i am passing form data
$data isn't an object, it is an array; Request::all() returns an array. You can't access an array with the same notation you would an object.
$this->data['message']; // access element of the array
Newsletter.php
<?php
namespace App\Mail;
use App\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Http\Request;
class Newsletter extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public $order;
public function __construct($order)
{
$this->order = $order;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('mail', $this->order)->subject($this->order['subject']);
}
}
SendReminderEmail.php
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Mail;
use App\Mail\Newsletter;
use App\User;
class SendReminderEmail implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* #return void
*/
public $order, $email;
public function __construct($order, $emails)
{
$this->order = $order;
$this->email = $emails;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
//for($i=0;$i<count($this->email);$i++)
Mail::to($this->email)->queue(new Newsletter($this->order));
}
}
Controller
public function sendSubMail(Request $request){
$data = ['text' => $request->input('message'), 'subject' => $request->input('subject')];
$emails = DB::table('emails')->get();
for ($i=0; $i < count($emails); $i++) {
try {
Mail::to($emails[$i])->queue(new Newsletter($data));
//dispatch((new Job)->onQueue('high'))
dispatch(new SendReminderEmail($data, $emails[$i]));
} catch (Exception $e) {
}
}
return view('emailSent', ['sub' => 'Emails successfully sent']);
}
Can anyone explain me how to create an Email queue in laravel. I tried many ways but none of them seems to work.
I'm trying to send email using queues. I have to send more than 1500 in the request. but the queue which I implemented doesnt seem to work. Please help.
Thanks in advance
Using Cron to send mail One Method
Hello i was working with mailable and using queue but when i used php artisan queue:listen and send a mail it did not work like it was supposed to do, i did get the email on mailtrap, but there was no message in my console. I tried sending the mail first and then use my command but it worked without my command. and it does not take a while because its sending immediately here is my code
controller.php
use Illuminate\Support\Facades\Mail;
use App\Mail\testmail;
class Controller extends Controller{
public function email($email, Request $request){
$emailuser = $request->input('email');
$message = $request->input('bericht');
mail::to($email)->queue(new testmail($emailuser, $message));
}
}
testmail.php
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class testmail extends Mailable
{
use Queueable, SerializesModels;
public $emailuser;
public $message;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($emailuser, $message)
{
$this->emailuser = $emailuser;
$this->message = $message;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->markdown('email.mail');
}
}
mail.blade.php
#component('mail::message')
{{ $emailuser }}
{{ $message }}
Thanks,<br>
{{ config('app.name') }}
#endcomponent
does anyone know how to fixs this because i need it to have a delay for my application
Use a job instead of Maillable and in that job in handle function write down the code to send the email in that job
for i.e-:
$job = (new SendWelcomeEmail($activation->code,$user))->onQueue('default');
and the job file SendwelcomeEmail would like following-:
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Jobs\Job;
use Mail;
class SendWelcomeEmail extends Job implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* #return void
*/
protected $activation_code;
protected $user;
public function __construct($activation_code,$user)
{
$this->activation_code=$activation_code;
$this->user=$user;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
try{
$user=$this->user;
Mail::send('emails.user.register', ['activation_code' => $this->activation_code,'user'=>$this->user], function ($m) use ($user) {
$m->to($user->email,$user->first_name." ".$user->last_name)
->subject(trans('emails.USER_REGISTER_SUBJECT',['project'=>trans('project.project_name')]));
});
\Log::useDailyFiles(storage_path().'/logs/user-registration/success/'.date('Y-m-d').'.log');
\Log::info('Welcome Email Send to-:'.$user->email);
}catch(Exception $ex){
\Log::useDailyFiles(storage_path().'/logs/user-registration/error/'.date('Y-m-d').'.log');
\Log::error($ex->getMessage());
\Log::error("Line Number->".$ex->getLine());
}
}
}
I have to update from 5.1 to 5.4
This was code for mail with`5.1
Mail::queue('emails.welcome_client', compact('user', 'userPassword'), function ($message) use ($user, $adminEmails) {
$message->subject('Welcome to Enterprise Solutions!');
$message->from(env('MAIL_FROM_ADDRESS'), env('MAIL_FROM_NAME'));
$message->to($user->email);
foreach($adminEmails as $adminEmail) {
$message->bcc($adminEmail);
}
});
I have to change from Laravel 5.1 to 5.4
so I create object mail
here it is
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class ClientMail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public $user;
// protected $content;
public function __construct($user)
{
$this->content = $user;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from(('MAIL_FROM_ADDRESS'), env('MAIL_FROM_NAME'))
->subject('Welcome to Enterprise Solutions!')
->view('emails.welcome_client');
}
}
and in controller I do this
Mail::to($user->email)
->bcc($adminEmail)
->queue(new ClientMail($adminEmails));
when I try to run I get this error: Undefined $adminEmail. How I can fix this problem?
Try this one:
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class ClientMail extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$this->from(('MAIL_FROM_ADDRESS'), env('MAIL_FROM_NAME'))
->subject('Welcome to Enterprise Solutions!')
->view('emails.welcome_client');
return $this;
}
}
And in Controller call:
Mail::to($user->email)->bcc($adminEmails)->queue(new ClientMail());